如何使用Python发送电子邮件? [英] How to send an email with Python?
问题描述
此代码可以正常发送给我一个电子邮件:
import smtplib
/ pre>
#SERVER =localhost
FROM ='monty@python.com'
TO = [jon@mycompany.com]#必须是列表
SUBJECT =你好!
TEXT =这个消息是用Python的smtplib发送的。
#准备实际的消息
message =\
从:%s
至:%s
主题:% s
%s
%(FROM,,.join(TO),SUBJECT,TEXT)
#发送邮件
server = smtplib.SMTP('myserver')
server.sendmail(FROM,TO,message)
server.quit()
但是,如果我尝试将其包装在这样的函数中:
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
这是函数
message =中的一些测试文档\
从:%s
至:%s
主题:%s
%s
%(FROM,,.join ($)
#发送邮件
server = smtplib.SMTP(SERVER)
server.sendmail(FROM,TO,message)
server.quit()
并调用它会收到以下错误:
追溯(最近最近通话):
文件C:/Python31/mailtest1.py,第8行,< module>
sendmail.sendMail(发件人,收件人,主题,正文和服务器)
文件C:/Python31\sendmail.py,第13行,sendMail
server.sendmail(FROM, TO,message)
文件C:\Python31\lib\smtplib.py,第720行,在sendmail
self.rset()
文件C:\Python31 \lib\smtplib.py,第444行,rset
return self.docmd(rset)
文件C:\Python31\lib\smtplib.py,行368,in docmd
return self.getreply()
文件C:\Python31\lib\smtplib.py,第345行,getreply
raise SMTPServerDisconnected(Connection unexpectedly关闭)
smtplib.SMTPServerDisconnected:连接意外关闭
任何人都可以帮我理解为什么?
解决方案我建议您使用标准软件包
电子邮件
和smtplib
一起发送电子邮件。请看下面的例子(转载自 Python文档)。请注意,如果您遵循这种方法,简单任务确实很简单,而且更复杂的任务(如附加二进制对象或发送简单/ HTML多部分消息)可以非常快速地完成。#导入实际发送功能的smtplib
import smtplib
#导入我们需要的电子邮件模块
从email.mime.text import MIMEText
#打开一个纯文本文件进行阅读。对于这个例子,假设
#文本文件只包含ASCII字符。
with open(textfile'rb')as fp:
#创建一个文本/纯文本
msg = MIMEText(fp.read())
#我==发件人的电子邮件地址
#你==收件人的电子邮件地址
msg ['Subject'] ='%s'的内容%textfile
msg ['From'] =我
msg ['To'] =你
#通过我们自己的SMTP服务器发送消息,但不要包含
#信头。
s = smtplib.SMTP('localhost')
s.sendmail(我,[你],msg.as_string())
s.quit()
要发送电子邮件到多个目的地,您还可以按照 Python文档:
#导入smtplib for实际发送功能
import smtplib
#这是我们需要的电子邮件包模块
from email.mime.image import MIMEImage
from email.mime。 multipart import MIMEMultipart
COMMASPACE =','
#创建容器(外部)电子邮件。
msg = MIMEMultipart()
msg ['Subject'] ='我们的家庭团聚'
#me ==发件人的电子邮件地址
#family =所有收件人的列表电子邮件地址
msg ['From'] = me
msg ['To'] = COMMASPACE.join(family)
msg.preamble ='我们的家庭团聚'
#假设我们知道图像文件都是PNG格式的
,用于pngfiles中的文件:
#以二进制模式打开文件。让MIMEImage类自动
#猜测具体的图像类型。
with open(file,'rb')as fp:
img = MIMEImage(fp.read())
msg.attach(img)
#发送电子邮件通过我们自己的SMTP服务器。
s = smtplib.SMTP('localhost')
s.sendmail(me,family,msg.as_string())
s.quit()
如您所见,
MIMEText 中的
/ code>对象必须是由逗号分隔的电子邮件地址组成的字符串。另一方面,
sendmail
函数的第二个参数必须是字符串列表(每个字符串都是电子邮件地址)。
所以,如果你有三个电子邮件地址:
person1@example.com
,person2@example.com
和person3@example.com
,您可以执行以下操作(省略明确的部分):to = [person1@example.com,person2@example.com,person3@example.com]
msg ['To'] =,。 (to)
s.sendmail(me,to,msg.as_string())
,。join(to)
part将列表中的单个字符串以逗号分隔。
从你的问题我收集到你没有经过Python教程 - 如果你想在Python中的任何地方,这是必须的 - 文档对标准库来说非常出色。This code works and sends me an email just fine:
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
Can anyone help me understand why?
解决方案I recommend that you use the standard packages
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 COMMASPACE = ', ' # 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'] = COMMASPACE.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 theMIMEText
object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to thesendmail
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
, andperson3@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.
这篇关于如何使用Python发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!