import smtplib
#SERVER = "localhost"
FROM ='monty@python.com'
TO =["jon@mycompany.com"]# must be a list
SUBJECT ="Hello!"
TEXT ="This message was sent with Python's smtplib."# Prepare actual message
message ="""\
From: %s
To: %s
Subject: %s
%s
"""%(FROM,", ".join(TO), SUBJECT, TEXT)# Send the mail
server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()
但是,如果我尝试将其包装在这样的函数中:
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):import smtplib
"""this is some test documentation in the function"""
message ="""\
From: %s
To: %s
Subject: %s
%s
"""%(FROM,", ".join(TO), SUBJECT, TEXT)# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
并称其为以下错误:
Traceback(most recent call last):File"C:/Python31/mailtest1.py", line 8,in<module>
sendmail.sendMail(sender,recipients,subject,body,server)File"C:/Python31\sendmail.py", line 13,in sendMail
server.sendmail(FROM, TO, message)File"C:\Python31\lib\smtplib.py", line 720,in sendmail
self.rset()File"C:\Python31\lib\smtplib.py", line 444,in rset
return self.docmd("rset")File"C:\Python31\lib\smtplib.py", line 368,in docmd
return self.getreply()File"C:\Python31\lib\smtplib.py", line 345,in getreply
raiseSMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected:Connection unexpectedly closed
import smtplib
#SERVER = "localhost"
FROM = 'monty@python.com'
TO = ["jon@mycompany.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()
However if I try to wrap it in a function like this:
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
and call it I get the following errors:
Traceback (most recent call last):
File "C:/Python31/mailtest1.py", line 8, in <module>
sendmail.sendMail(sender,recipients,subject,body,server)
File "C:/Python31\sendmail.py", line 13, in sendMail
server.sendmail(FROM, TO, message)
File "C:\Python31\lib\smtplib.py", line 720, in sendmail
self.rset()
File "C:\Python31\lib\smtplib.py", line 444, in rset
return self.docmd("rset")
File "C:\Python31\lib\smtplib.py", line 368, in docmd
return self.getreply()
File "C:\Python31\lib\smtplib.py", line 345, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
# Import smtplib for the actual sending functionimport smtplib
# Import the email modules we'll needfrom email.mime.text importMIMEText# Open a plain text file for reading. For this example, assume that# the text file contains only ASCII characters.with open(textfile,'rb')as fp:# Create a text/plain message
msg =MIMEText(fp.read())# me == the sender's email address# you == the recipient's email address
msg['Subject']='The contents of %s'% textfile
msg['From']= me
msg['To']= you
# Send the message via our own SMTP server, but don't include the# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me,[you], msg.as_string())
s.quit()
# Import smtplib for the actual sending functionimport smtplib
# Here are the email package modules we'll needfrom email.mime.image importMIMEImagefrom email.mime.multipart importMIMEMultipart# Create the container (outer) email message.
msg =MIMEMultipart()
msg['Subject']='Our family reunion'# me == the sender's email address# family = the list of all recipients' email addresses
msg['From']= me
msg['To']=', '.join(family)
msg.preamble ='Our family reunion'# Assume we know that the image files are all in PNG formatfor file in pngfiles:# Open the files in binary mode. Let the MIMEImage class automatically# guess the specific image type.with open(file,'rb')as fp:
img =MIMEImage(fp.read())
msg.attach(img)# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
I recommend that you use the standard packages email and smtplib together to send email. Please look at the following example (reproduced from the Python documentation). Notice that if you follow this approach, the “simple” task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
with open(textfile, 'rb') as fp:
# Create a text/plain message
msg = MIMEText(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
For sending email to multiple destinations, you can also follow the example in the Python documentation:
# Import smtplib for the actual sending function
import smtplib
# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'
# Assume we know that the image files are all in PNG format
for file in pngfiles:
# Open the files in binary mode. Let the MIMEImage class automatically
# guess the specific image type.
with open(file, 'rb') as fp:
img = MIMEImage(fp.read())
msg.attach(img)
# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
As you can see, the header To in the MIMEText object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail function must be a list of strings (each string is an email address).
So, if you have three email addresses: person1@example.com, person2@example.com, and person3@example.com, you can do as follows (obvious sections omitted):
to = ["person1@example.com", "person2@example.com", "person3@example.com"]
msg['To'] = ",".join(to)
s.sendmail(me, to, msg.as_string())
the ",".join(to) part makes a single string out of the list, separated by commas.
From your questions I gather that you have not gone through the Python tutorial – it is a MUST if you want to get anywhere in Python – the documentation is mostly excellent for the standard library.
def send_simple_message():return requests.post("https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api","YOUR_API_KEY"),
data={"from":"Excited User <mailgun@YOUR_DOMAIN_NAME>","to":["bar@example.com","YOU@YOUR_DOMAIN_NAME"],"subject":"Hello","text":"Testing some Mailgun awesomness!"})
Well, you want to have an answer that is up-to-date and modern.
Here is my answer:
When I need to mail in Python, I use the mailgun API wich get’s a lot of the headaches with sending mails sorted out. They have a wonderfull app/api that allows you to send 5,000 free emails per month.
contents =['Body text, and here is an embedded image:','http://somedomain/image.png','You can also find an audio file attached.','/local/path/song.mp3']
I’d like to help you with sending emails by advising the yagmail package (I’m the maintainer, sorry for the advertising, but I feel it can really help!).
Note that I provide defaults for all arguments, for example if you want to send to yourself, you can omit TO, if you don’t want a subject, you can omit it also.
Furthermore, the goal is also to make it really easy to attach html code or images (and other files).
Where you put contents you can do something like:
contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',
'You can also find an audio file attached.', '/local/path/song.mp3']
Wow, how easy it is to send attachments! This would take like 20 lines without yagmail ;)
Also, if you set it up once, you’ll never have to enter the password again (and have it safely stored). In your case you can do something like:
I’d invite you to have a look at the github or install it directly with pip install yagmail.
回答 3
存在压痕问题。下面的代码将起作用:
import textwrap
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):import smtplib
"""this is some test documentation in the function"""
message = textwrap.dedent("""\
From: %s
To: %s
Subject: %s
%s
"""%(FROM,", ".join(TO), SUBJECT, TEXT))# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
There is indentation problem. The code below will work:
import textwrap
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = textwrap.dedent("""\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT))
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
回答 4
这是Python上的示例3.x,比以下示例简单得多2.x:
import smtplib
from email.message importEmailMessagedef send_mail(to_email, subject, message, server='smtp.example.cn',
from_email='xx@example.com'):# import smtplib
msg =EmailMessage()
msg['Subject']= subject
msg['From']= from_email
msg['To']=', '.join(to_email)
msg.set_content(message)print(msg)
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.login(from_email,'password')# user & password
server.send_message(msg)
server.quit()print('successfully sent the mail.')
调用此函数:
send_mail(to_email=['12345@qq.com','12345@126.com'],
subject='hello', message='Your analysis has done!')
import smtplib
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):"""this is some test documentation in the function"""
message ="""\
From: %s
To: %s
Subject: %s
%s
"""%(FROM,", ".join(TO), SUBJECT, TEXT)# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
现在展开不会发生,您发送
From: monty@python.com
To: jon@mycompany.com
Subject: Hello!
This message was sent with Python's smtplib.
While indenting your code in the function (which is ok), you did also indent the lines of the raw message string. But leading white space implies folding (concatenation) of the header lines, as described in sections 2.2.3 and 3.2.3 of RFC 2822 – Internet Message Format:
Each header field is logically a single line of characters comprising
the field name, the colon, and the field body. For convenience
however, and to deal with the 998/78 character limitations per line,
the field body portion of a header field can be split into a multiple
line representation; this is called “folding”.
In the function form of your sendmail call, all lines are starting with white space and so are “unfolded” (concatenated) and you are trying to send
From: monty@python.com To: jon@mycompany.com Subject: Hello! This message was sent with Python's smtplib.
Other than our mind suggests, smtplib will not understand the To: and Subject: headers any longer, because these names are only recognized at the beginning of a line. Instead smtplib will assume a very long sender email address:
monty@python.com To: jon@mycompany.com Subject: Hello! This message was sent with Python's smtplib.
This won’t work and so comes your Exception.
The solution is simple: Just preserve the message string as it was before. This can be done by a function (as Zeeshan suggested) or right away in the source code:
import smtplib
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Now the unfolding does not occur and you send
From: monty@python.com
To: jon@mycompany.com
Subject: Hello!
This message was sent with Python's smtplib.
which is what works and what was done by your old code.
Note that I was also preserving the empty line between headers and body to accommodate section 3.5 of the RFC (which is required) and put the include outside the function according to the Python style guide PEP-0008 (which is optional).
import smtplib
#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com',587)#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()#Next, log in to the server
server.login("#email","#password")
msg ="Hello! This Message was sent by the help of Python"#Send the mail
server.sendmail("#Sender","#Reciever", msg)
Make sure you have granted permission for both Sender and Receiver to send email and receive email from Unknown sources(External Sources) in Email Account.
import smtplib
#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)
#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()
#Next, log in to the server
server.login("#email", "#password")
msg = "Hello! This Message was sent by the help of Python"
#Send the mail
server.sendmail("#Sender", "#Reciever", msg)
Thought I’d put in my two bits here since I have just figured out how this works.
It appears that you don’t have the port specified on your SERVER connection settings, this effected me a little bit when I was trying to connect to my SMTP server that isn’t using the default port: 25.
According to the smtplib.SMTP docs, your ehlo or helo request/response should automatically be taken care of, so you shouldn’t have to worry about this (but might be something to confirm if all else fails).
Another thing to ask yourself is have you allowed SMTP connections on your SMTP server itself? For some sites like GMAIL and ZOHO you have to actually go in and activate the IMAP connections within the email account. Your mail server might not allow SMTP connections that don’t come from ‘localhost’ perhaps? Something to look into.
The final thing is you might want to try and initiate the connection on TLS. Most servers now require this type of authentication.
You’ll see I’ve jammed two TO fields into my email. The msg[‘TO’] and msg[‘FROM’] msg dictionary items allows the correct information to show up in the headers of the email itself, which one sees on the receiving end of the email in the To/From fields (you might even be able to add a Reply To field in here. The TO and FROM fields themselves are what the server requires. I know I’ve heard of some email servers rejecting emails if they don’t have the proper email headers in place.
This is the code I’ve used, in a function, that works for me to email the content of a *.txt file using my local computer and a remote SMTP server (ZOHO as shown):
def emailResults(folder, filename):
# body of the message
doc = folder + filename + '.txt'
with open(doc, 'r') as readText:
msg = MIMEText(readText.read())
# headers
TO = 'to_user@domain.com'
msg['To'] = TO
FROM = 'from_user@domain.com'
msg['From'] = FROM
msg['Subject'] = 'email subject |' + filename
# SMTP
send = smtplib.SMTP('smtp.zoho.com', 587)
send.starttls()
send.login('from_user@domain.com', 'password')
send.sendmail(FROM, TO, msg.as_string())
send.quit()
It’s worth noting that the SMTP module supports the context manager so there is no need to manually call quit(), this will guarantee it is always called even if there is an exception.
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.ehlo()
server.login(user, password)
server.sendmail(from, to, body)
def getreply(self):"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""
As far your code is concerned, there doesn’t seem to be anything fundamentally wrong with it except that, it is unclear how you’re actually calling that function. All I can think of is that when your server is not responding then you will get this SMTPServerDisconnected error. If you lookup the getreply() function in smtplib (excerpt below), you will get an idea.
def getreply(self):
"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""