Trying to send an email with python [duplicate] - python

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'?

Related

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

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.

Sending an email in Iron Python taking forever

So I'm trying to send an email in Iron Python 2.7, and nothing has worked for me. So I combined a bunch of different bits of code I got to try and workaround my issue. Basically, I need to send a zip file without using localhost because I'm assuming the client computer won't have localhost.
Here is my code:
# Send an email
def sendEmail():
# Set standard variables
send_to = ["*******#live.com"]
send_from = "********#outlook.com"
subject = "New Game Info"
text = "Some new info for you. This is an automated message."
assert isinstance(send_to, list)
msg = MIMEMultipart(
From=send_from,
To=COMMASPACE.join(send_to),
Date=formatdate(localtime=True),
Subject=subject
)
print "Created MIME..."
msg.attach(MIMEText(text))
print "Attached message..."
with open("TempLog.zip", "rb") as fil:
msg.attach(MIMEApplication(
fil.read(),
Content_Disposition='attachment; filename="%s"' % "TempLog.zip"
))
print "Attached file..."
server = smtplib.SMTP()
server.connect("smtp-mail.outlook.com", 587)
server.starttls()
server.login("*********#outlook.com", "*****")
server.sendmail("********#outlook.com", send_to, msg.as_string())
server.close()
So as you can see, I have put print statements everywhere to locate the issue. It gets up to "Attached file...," but no further.
I appreciate any help with this issue.
I would suggest using a try/catch block to figure out what the problem really is.
With your current code:
try:
server = smtplib.SMTP()
server.connect("smtp-mail.outlook.com", 587)
server.starttls()
server.login("*********#outlook.com", "*****")
server.sendmail("********#outlook.com", send_to, msg.as_string())
server.close()
except SMTPException, err:
print "ERROR: Unable to send mail - %s" %(err)
except Exception, err:
print "Some other error - %s" %(err)
And for an example that I would suggest putting your host options in the SMTP initialization instead of doing so in connect(). You can modify this example to utilize starttls() as you need.
try:
smtp = smtplib.SMTP(host, port)
smtp.sendmail(sender, receivers, message)
print "Successfully sent email to '%s'" %(receivers)
except SMTPException, err:
print "ERROR: Unable to send mail - %s" %(err)
except Exception, err:
print "Some other error - %s" %(err)
I'm the maintainer of yagmail, a package that tries to make it really easy to send emails.
Maybe you can try this:
import yagmail
yag = yagmail.SMTP(send_from, password, host = 'smtp-mail.outlook.com')
yag.send(send_to, subject = subject, contents = [text, "TempLog.zip"])
This should automatically have "text" as body, and when you give it the location of TempLog.zip, it will automatically detect it is a zip file and attach it.
You might have to install it:
pip install yagmail # Python 2
pip3 install yagmail # Python 3
If something does not work (or when it does), please let me know! I will certainly try to help more.

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.

How can I send email using Python?

I am writing a program that sends an email using Python. What I have learned from various forums is the following piece of code:
#!/usr/bin/env python
import smtplib
sender = "sachinites#gmail.com"
receivers = ["abhisheks#cse.iitb.ac.in"]
yourname = "Abhishek Sagar"
recvname = "receptionist"
sub = "Testing email"
body = "who cares"
message = "From: " + yourname + "\n"
message = message + "To: " + recvname + "\n"
message = message + "Subject: " + sub + "\n"
message = message + body
try:
print "Sending email to " + recvname + "...",
server = smtplib.SMTP('smtp.gmail.com:587')
username = 'XYZ#gmail.com'
password = '*****'
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(sender, receivers, message)
server.quit()
print "successfully sent!"
except Exception:
print "Error: unable to send email"
But it is simply printing ""Error: unable to send email" and exits out on the terminal. How might I resolve this?
I modified the last two lines to
except Exception, error:
print "Unable to send e-mail: '%s'." % str(error)
I get the following error message :
Traceback (most recent call last):
File "./2.py", line 45, in <module>
smtpObj = smtplib.SMTP('localhost')
File "/usr/lib/python2.6/smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 111] Connection refused
If message headers, payload contain non-ascii characters then they should be encoded:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
login, password = 'user#gmail.com', getpass('Gmail password:')
recipients = [login]
# create message
msg = MIMEText('message body…', 'plain', 'utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ", ".join(recipients)
# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
s.login(login, password)
s.sendmail(msg['From'], recipients, msg.as_string())
finally:
s.quit()
If you print the error message, you will likely get a comprehensive description of what error occurred. Try (no pun intended) this:
try:
# ...
except Exception, error:
print "Unable to send e-mail: '%s'." % str(error)
If, after reading the error message, you still do not understand your error, please update your question with the error message and we can help you some more.
Update after additional information:
the error message
socket.error: [Errno 111] Connection refused
means the remote end (e.g. the GMail SMTP server) is refusing the network connection. If you take a look at the smtplib.SMTP constructor, it seems you should change
server = smtplib.SMTP('smtp.gmail.com:587')
to the following.
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
According to the error message, you use the localhost as the SMTP server, then the connection was refused. Your localhost didn't have an SMTP sever running I guess, you need to make sure the SMTP server you connect is valid.

Failing to send email with the Python example

I've been trying (and failing) to figure out how to send email via Python.
Trying the example from here:
http://docs.python.org/library/smtplib.html#smtplib.SMTP
but added the line server = smtplib.SMTP_SSL('smtp.gmail.com', 465) after I got a bounceback about not having an SSL connection.
Now I'm getting this:
Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
Thoughts?
server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).
I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.
"
import smtplib
mailuser = 'MYEMAIL#gmail.com'
mailpasswd = 'MYPASSWORD'
fromaddr = 'MYEMAIL#gmail.com'
toaddrs = 'MYEMAIL2#gmail.com'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
"
and then I get this error message: "
Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
"
note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP underscore SSL underscore PORT=587", there's some sort of formatting thing going on here.
The following code works for me:
import smtplib
FROMADDR = "my.real.address#gmail.com"
LOGIN = FROMADDR
PASSWORD = "my.real.password"
TOADDRS = ["my.real.address#gmail.com"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
I'm using Python 2.5.2.
Edit: changed port from 25 to 587 as suggested by ΤΖΩΤΖΙΟΥ, and dropped the second ehlo(). Now I would love to know why port 25 works perfectly from my machine (and port 465 does not).
The correct way to connect to GMail using SSL is:
server = smtplib.SMTP('smtp.gmail.com', 587)
Port 465 seems to cause delays. Both ports are specified in a GMail FAQ.
Note that use of port 587 is more common for SMTP over SSL, although this is just trivial information, it has no other practical use.
This answer is provided as community wiki in order to be chosen as "the" answer. Please improve as needed.
The problem is due to a bug in Python. Trying to create a connection with SMTP_SSL will fail with "SMTPServerDisconnected: please run connect() first."
A fix has been committed, so you can patch your local copy. See the attachment named "smtplib_72551.diff".
(Note: SMTP_SSL is a new class added to Python 2.6/3.0 and later.)
Here's a simple throw away solution. Meant to paste this earlier, but fell asleep at my chair.
import smtplib
import email
import os
username = "user#gmail.com"
passwd = "password"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
server = smtplib.SMTP("smtp.gmail.com", 495)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, passwd)
server.sendmail(username, to, msg.as_string())
server.close()
mail("you", "hi", "hi", "webcam.jpg")
It's my assumption that most people on this thread that have had successful attempts with their code aren't on win32. ;)
*edit: See http://docs.python.org/library/email-examples.html for some good "official" examples.
Okay, found out that this line of code does the trick!
server = smtplib.SMTP('smtp.gmail.com', 587 )
Turned out to be GMAIL didn't support SSL on port 25 (and port 465 caused a hang for some reason).
Thanks guys!
You should check your port, I'm not sure that google's SMTP port is 65, that would explain the timeout.
Modify your sources as such:
smtplib.SMTP_SSL('smtp.google.com', 465)
If, however, you are certain that it ought to work and it doesn't, it appears that there are some problems with smtplib.SMTP_SSL, and there's an available patch for it here.
Incorrect port maybe? I'm using 587 for smtp.gmail.com and it works.
from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText
HOST = 'smtp.gmail.com'
PORT = 465
USERNAME = 'oltjano13#gmail.com'
PASSWORD = ''
SENDER = 'oltjano13#gmail.com'
RECIPIENT = 'oltjano13#gmail.com'
text_subtype = 'plain'
with open('textfile', 'rb') as f:
msg = MIMEText(f.read(), text_subtype)
msg['Subject'] = 'Python Script'
msg['From'] = SENDER
msg['To'] = RECIPIENT
try:
connection = SMTP(HOST, PORT)
connection.login(USERNAME, PASSWORD)
connection.sendmail(SENDER, RECIPIENT, msg.as_string())
except Exception, e:
print(e)
The above code works fine for me. As you can see the PORT = 465 is being used in this example since I am using SSL. If you plan to use the port 587 then TLS is required.
import smtplib
content = 'example email stuff here'
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('email#gmail.com','password')
mail.sendmail('email#gmail.com', 'email#yahoo.com', content)
mail.close()
Then I had trie to sent email through smtp.gmail.com, I had the same errors. In my case the Internet provider had close the port 25 (and also 587 and other) for outgoing connections from the IP addresses (from my network) to the external network, leaving open the 25th port only for its mail server.
So, at first try:
telnet smtp.gmail.com 587
(587 it your port)
By doing this you can understand, if your port is closed by the Internet provider.
You can contact your provider and ask them to open a port for you.
My solution was connecting to other network (with open port)
Here is the code I used:
gmailaddress = "youremailadress#gmail.com"
gmailpassword = "7777777"
mailto = "youremailadress#gmail.com"
msg = input("What is your message? \n ")
mailServer = smtplib.SMTP('smtp.gmail.com' , 587)
mailServer.starttls()
mailServer.login(gmailaddress , gmailpassword)
mailServer.sendmail(gmailaddress, mailto , msg)
print(" \n Sent!")
mailServer.quit()```
After a lot of fiddling with the examples e.g here
this now works for me:
import smtplib
from email.mime.text import MIMEText
# SMTP sendmail server mail relay
host = 'mail.server.com'
port = 587 # starttls not SSL 465 e.g gmail,port 25 blocked by most ISPs & AWS
sender_email = 'name#server.com'
recipient_email = 'name#domain.com'
password = 'YourSMTPServerAuthenticationPass'
subject = "Server - "
body = "Message from server"
def sendemail(host, port, sender_email, recipient_email, password, subject, body):
try:
p1 = f'<p><HR><BR>{recipient_email}<BR>'
p2 = f'<h2><font color="green">{subject}</font></h2>'
p3 = f'<p>{body}'
p4 = f'<p>Kind Regards,<BR><BR>{sender_email}<BR><HR>'
message = MIMEText((p1+p2+p3+p4), 'html')
# servers may not accept non RFC 5321 / RFC 5322 / compliant TXT & HTML typos
message['From'] = f'Sender Name <{sender_email}>'
message['To'] = f'Receiver Name <{recipient_email}>'
message['Cc'] = f'Receiver2 Name <>'
message['Subject'] = f'{subject}'
msg = message.as_string()
server = smtplib.SMTP(host, port)
print("Connection Status: Connected")
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login(sender_email, password)
print("Connection Status: Logged in")
server.sendmail(sender_email, recipient_email, msg)
print("Status: Email as HTML successfully sent")
except Exception as e:
print(e)
print("Error: unable to send email")
# Run
sendemail(host, port, sender_email, recipient_email, password, subject, body)
print("Status: Exit")

Categories