Python 3, sending an email through a Gmail hosted college account - python

so recently I have been trying to send emails using Python 3.6 through my college email account my_email#my_college.edu. This account is hosted on google, so I can use it with Gmail, Drive, etc. As such I thought it would be simple enough to write a simple program that would accomplish what I wanted, but nothing seems to be working. Here is the basic code that I found on practically every tutorial website:
import smtplib
TO = 'receiver_email'
SUBJECT = 'TEST MAIL'
TEXT = 'Here is a message from python.'
# Gmail Sign In
gmail_sender = 'my_email#my_college.edu'
gmail_passwd = 'my_password'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join(['To: %s' % TO,
'From: %s' % gmail_sender,
'Subject: %s' % SUBJECT,
'', TEXT])
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('email sent')
except:
print ('error sending mail')
server.quit()
Whenever I run this, I get a "bad credentials" error. Specifically the error I get is this one:
Traceback (most recent call last):
File "D:\Coding Files\Projects in Progress\autoEmail.py", line 14, in
<module>
server.login(gmail_sender, gmail_passwd)
File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-
32\lib\smtplib.py", line 730, in login
raise last_exception
File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-
32\lib\smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "C:\Users\Joe\AppData\Local\Programs\Python\Python36-
32\lib\smtplib.py", line 642, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not
accepted. Learn more at\n5.7.8 https://support.google.com/mail/?
p=BadCredentials g8sm9220621qtg.23 - gsmtp')
I tried working with the Gmail API, and that was able to get me Gmail credentials and sign me in to a chrome page, but I couldn't seem to find a sufficient tutorial that I was able to understand using the Gmail API.
Any help would be very appreciated! Thank you

Try changing the server from smtp.gmail.com to my_college.edu (or maybe something.my_college.edu, or something like that). I've configured stuff that needs email server URLs with school Gmails and it worked like that, if I remember correctly.

Related

smtplib.SMTPConnectError: (421, b'Service not available') while using my pycharm to send a mail with python

i got the above error each time i try sending a mail using python. am somewhat new to this whole smtp thing. below is my code. please help.
import smtplib
my_email ="okoyekennethoptimizer#gmail.com"
password = "nmmrjdphptwfgjgb"
connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.starttls()
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs="okoyek10#yahoomail.com", msg="hello")
connection.close()
please help. its been giving me tough time
Try creating an "App password" after enabling 2-step auth in your Gmail. You still need to do some lookup but generally, this should help.
The trick is in:
Enabling less secure apps.
Make sure your account has 2FA.
Generating an app password under My Google Account>>Security under Signing in to Google.
Replace the 16-digit password with the password you've placed in the password variable.
Just before connection.starttls() add connection.ehlo().
A code for example:
my_email ="okoyekennethoptimizer#gmail.com"
app_password = "16-digit-app-password"
connection = smtplib.SMTP("smtp.gmail.com", 587)
connection.ehlo()
connection.starttls()
connection.login(user=my_email, password=app_password)
Also you SHOULD create From:, To:, and Subject: message headers, separated from the message body by a blank line.
E.g.
msg = "\r\n".join([
"From: user_me#gmail.com",
"To: user_you#gmail.com",
"Subject: Any subject",
"",
"Good Evening, how are you?"
])

Gmail SMTP authentication always fail

I created this software in python 3
import smtplib
TO = 'anywhere#mail.com'
SUBJECT = 'Text subject of the mail'
TEXT = 'Text of the mail'
gmail_sender = 'yourMail#gmail.com'
gmail_passwd = 'password'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join(['To: %s' % TO,
'From: %s' % gmail_sender,
'Subject: %s' % SUBJECT,
'', TEXT])
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('email sent')
except:
print ('error sending mail')
server.quit()
The first day the software worked well but now I always have an authentification error from gmail :
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o81-v6sm9180362wmo.38 - gsmtp')
What I did already is :
I desactivated the unlock captchar from this link :
https://accounts.google.com/DisplayUnlockCaptcha
and I have enabled the less secure apps from this link:
https://www.google.com/settings/security/lesssecureapps
But still the same, I can't send an e-mail anymore. It doesn't seems that there's a Python software problem because I wrote the same software in Go and I still receive the same error.
It’s solved. My login was wrong.

Python sending email via Gmail failed

I am using this piece of code:
import smtplib
fromaddr = 'fromuser#gmail.com'
toaddrs = 'myemail#gmail.com'
msg = 'There was a terrible error that occured and I wanted you to know!'
# Credentials (if needed)
username = 'myusername'
password = 'passwd'
# The actual mail send
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
I am receiving this error:
Traceback (most recent call last): File "C:/Python34/sendemail.py",
line 15, in
server.starttls() File "C:\Python34\lib\smtplib.py", line 673, in starttls
raise SMTPException("STARTTLS extension not supported by server.") smtplib.SMTPException: STARTTLS extension not supported by server.
When I do exculde server.starttls() I am receiving different error message about authentication. I have another price of code when I am accessing Gmail via web browser using webdriver and credentials works, so I copied and pasted to this code to make sure that credentials are correct.
I can't figure out why this is not working.
Thanks in advance.
you'll have to see here as well
use port 587
server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
Sending via Gmail works for me when using this code. Note that I use smtplib.SMTP() as opposed to smtplib.SMTP_SSL('smtp.gmail.com',465). Also try to use port 587 and not 465.
server = smtplib.SMTP()
server.connect(server, port)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(send_from, send_to, msg)
server.close()
Though I do find that using the emails library is much easier.
Please, try yagmail. Disclaimer: I'm the maintainer, but I feel like it can help everyone out!
It really provides a lot of defaults: I'm quite sure you'll be able to send an email directly with:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
You'll have to install yagmail first with either:
pip install yagmail # python 2
pip3 install yagmail # python 3
Once you will want to also embed html/images or add attachments, you'll really love the package!
It will also make it a lot safer by preventing you from having to have your password in the code.
It's either you use smtplib.SMTP() then starttls() (which I don't recommend), or you use smtplib.SMTP_SSL() alone ( dont't use starttls() after that)

how to send email attachement using python 2.7

I am getting error when using this code to send email using localhost ip, any suggestion how to solve the socket error?
def SendTMail(self):
# Import the email modules we'll need
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
#try:
fp = open('testint.txt', 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
testfile = 'TESTING REPORT'
fp.close()
me = '124#hotmail.co.uk'
you = '123#live.com'
msg['Subject'] = 'The contents of %s' % testfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('192.168.1.3')
s.sendmail(me, [you], msg.as_string())
s.quit()
the error is shown below:
File "x:\example.py", line 6, in SendTMail s = smtplib.SMTP('192.168.1.3')
File "x:\Python27\lib\smtplib.py", line 251, in init (code, msg) = self.connect(host, port)
File "x:\Python27\lib\smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout)
File "x:\Python27\lib\smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout)
File "x:\Python27\lib\socket.py", line 571, in create_connection raise err –
error: [Errno 10051] A socket operation was attempted to an unreachable network
Before posting raw code, I'd like to add an small explanation as per the conversation that took place in the comments to your question.
smtplib connects to an existing SMTP server. You can see it more like an Outlook Express. Outlook is a client (or a Mail User Agent, if you wanna get fancy). It doesn't send emails by itself. It connects to whatever SMTP server it has configured among its accounts and tells that server "Hey, I'm user xxx#hotmail.com (and here's my password to prove it). Could you send this for me?"
If you wanted to, having your own SMTP server is doable (for instance, in Linux, an easily configurable SMTP server would be Postfix, and I'm sure there are many for Windows) Once you set one up, it'll start listening for incoming connections in its port 25 (usually) and, if whatever bytes come through that port follow the SMTP protocol, it'll send it to its destination. IMHO, this isn't such a great idea (nowadays). The reason is that now, every (decent) email provider will consider emails coming from unverified SMTP servers as spam. If you want to send emails, is much better relying in a well known SMTP server (such as the one at smtp.live.com, the ones hotmail uses), authenticate against it with your username and password, and send your email relying (as in SMTP Relay) on it.
So this said, here's some code that sends an HTML text with an attachment borrajax.jpeg to an email account relying on smtp.live.com.
You'll need to edit the code below to set your hotmail's password (maybe your hotmail's username as well, if it's not 124#hotmail.co.uk as shown in your question) and email recipients. I removed mines from the code after my tests for obvious security reasons... for me :-D and I put back the ones I saw in your question. Also, this scripts assumes it'll find a .jpeg picture called borrajax.jpeg in the same directory where the Python script is being run:
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_mail():
test_str="This is a test"
me="124#hotmail.co.uk"
me_password="XXX" # Put YOUR hotmail password here
you="123#live.com"
msg = MIMEMultipart()
msg['Subject'] = test_str
msg['From'] = me
msg['To'] = you
msg.preamble = test_str
msg_txt = ("<html>"
"<head></head>"
"<body>"
"<h1>Yey!!</h1>"
"<p>%s</p>"
"</body>"
"</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg") as f:
msg.attach(MIMEImage(f.read()))
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"
smtp_conn.starttls()
smtp_conn.ehlo_or_helo_if_needed()
smtp_conn.login(me, me_password)
smtp_conn.sendmail(me, you, msg.as_string())
smtp_conn.quit()
if __name__ == "__main__":
send_mail()
When I run the example (as I said, I edited the recipient and the sender) it sent an email to a Gmail account using my (old) hotmail account. This is what I received in my Gmail:
There's a lot of stuff you can do with the email Python module. Have fun!!
EDIT:
Gorramit!! Your comment about attaching a text file wouldn't let me relax!! :-D I had to see it myself. Following what was detailed in this question, I added some code to add a text file as an attachment.
msg_txt = ("<html>"
"<head></head>"
"<body>"
"<h1>Yey!!</h1>"
"<p>%s</p>"
"</body>"
"</html>" % test_str)
msg.attach(MIMEText(msg_txt, 'html'))
with open("borrajax.jpeg", "r") as f:
msg.attach(MIMEImage(f.read()))
#
# Start new stuff
#
with open("foo.txt", "r") as f:
txt_attachment = MIMEText(f.read())
txt_attachment.add_header('Content-Disposition',
'attachment',
filename=f.name)
msg.attach(txt_attachment)
#
# End new stuff
#
smtp_conn = smtplib.SMTP("smtp.live.com", timeout=10)
print "connection stablished"
And yep, it works... I have a foo.txt file in the same directory where the script is run and it sends it properly as an attachment.

Trying to send an email with python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Send email with python
I'm trying so send an email with python but when I run the script it take a minute or two then I get this error:
Traceback (most recent call last):
File "./emailer", line 19, in <module>
server = smtplib.SMTP(SERVER)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 512, in create_connection
raise error, msg
socket.error: [Errno 60] Operation timed out
This is the script:
#!/usr/bin/env python
import smtplib
SERVER = 'addisonbean.com'
FROM = 'myemail#gmail.com'
TO = ['myemail#gmail.com']
SUBJECT = 'Hello!'
message = """\
Bla
Bla Bla
Bla Bla Bla
Bla Bla Bla Bla
"""
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
I also tried my site IP address as the server but that did the same thing.
Could someone tell me why it does this and how to fix this? Thanks!
Here's the key bit:
return socket.create_connection((port, host), timeout)
socket.error: [Errno 60] Operation timed out
Python's saying: I can't connect to that server, I've tried but it doesn't seem to respond.
Here's the second key bit:
SERVER = 'addisonbean.com'
That's not a mail server, is it?
While addisonbean.com does listen 25 port and answers 220 accra.dreamhost.com ESMTP - you seems to be behind proxy or some kind of firewall. Can you do telnet addisonbean.com 25 from your console?
It looks like you're hosting your page in dreamhost.com, a hosting provider.
When you set up your account, they probably gave you the chance to create email accounts ending with your domain (yaddayadda#addisonbean.com)
You may want to create one, get the information: host where the SMTP (the "mail server") is located, username, password... And you'll have to fill all that in your script.
I would recommend you start testing with another regular account (Gmail.com, Hotmail Outlook.com) and that you read (quite a bit) about what an SMTP server is (which is the server you'll have to talk to in order to have your email sent)
Here's a simple script that should send emails using a gmail account. Fill the information that is shown with asterisks with your data, see if it works:
#!/usr/bin/env python
import traceback
from smtplib import SMTP
from email.MIMEText import MIMEText
smtpHost = "smtp.gmail.com"
smtpPort = 587
smtpUsername = "***#gmail.com"
smtpPassword = "***"
sender = "***#gmail.com"
def sendEmail(to, subject, content):
retval = 1
if not(hasattr(to, "__iter__")):
to = [to]
destination = to
text_subtype = 'plain'
try:
msg = MIMEText(content, text_subtype)
msg['Subject'] = subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(host=smtpHost, port=smtpPort)
conn.set_debuglevel(True)
#conn.login(smtpUsername, smtpPassword)
try:
if smtpUsername is not False:
conn.ehlo()
if smtpPort != 25:
conn.starttls()
conn.ehlo()
if smtpUsername and smtpPassword:
conn.login(smtpUsername, smtpPassword)
else:
print("::sendEmail > Skipping authentication information because smtpUsername: %s, smtpPassword: %s" % (smtpUsername, smtpPassword))
conn.sendmail(sender, destination, msg.as_string())
retval = 0
except Exception, e:
print("::sendEmail > Got %s %s. Showing traceback:\n%s" % (type(e), e, traceback.format_exc()))
retval = 1
finally:
conn.close()
except Exception, e:
print("::sendEmail > Got %s %s. Showing traceback:\n%s" % (type(e), e, traceback.format_exc()))
retval = 1
return retval
if __name__ == "__main__":
sendEmail("***#gmail.com", "Subject: Test", "This is a simple test")
Once you have the equivalent information for your domain (smtpHost, smtpPort, smtpUsername...) it MAY work as well (depends on the port they're using, it may be 25, which is the default for non-encrypted connections... or not... You'll have to check with dreamhost.com for that)
Be aware that (since you're using a hosting that probably shares its SMTP server with other people) your "sender" may be yaddayadda#addisonbean.com but the actual information to connect to the dreamhost.com SMTP servers may be different: I'm guessing the 'smtpUsername' may be the username you use to login in your site admin, the 'smtpHost' may change to something like smtp.dreamhost.com or such... That I don't really know.
You have a lot of resources on how to do that.
You also seem to be a designer or photographer... One of those dudes people concern on how things look on the screen and all... Then you may wanna investigate what MiME emails are. You know... so the email is not sent with text only, but you can put fancy HTML in it... You know what I'm sayin'?

Categories