(参考:SMPT发送邮件)
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
这里我以qq邮箱为例,先附上代码:
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email import encoders
from email.utils import parseaddr, formataddr
from email.Utils import COMMASPACE,formatdate
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( \
Header(name, 'utf-8').encode(), \
addr.encode('utf-8') if isinstance(addr, unicode) else addr))
sender = '******@qq.com'
receiver = '******@qq.com'
subject = 'python email test'
smtpserver = 'smtp.qq.com'
username = '******@qq.com'
password = '*******'
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['Date'] = formatdate(localtime=True)
msg['From'] = _format_addr(u'Python爱好者 <%s>' % sender)
msg['To'] = _format_addr(u'管理员 <%s>' % receiver)
msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
smtp = smtplib.SMTP_SSL(smtpserver,465)
smtp.connect( smtpserver )
smtp.login( username, password )
smtp.sendmail( sender, receiver, msg.as_string() )
smtp.quit()
sender为发件人邮箱,receiver为收件人邮箱。smtpserver填qq邮箱服务器,发送邮件时需要开启POP3/SMTP服务。(设置方法:进入qq邮箱,设置—>账号,找到“POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务”模块,开启服务。)
填入username和password后运行,出现如下错误:
Traceback (most recent call last):
File "C:\Users\Desktop\0619\testemail.py", line 31, in <module>
smtp.login( username, password )
File "D:\toolsforwork\Python27\lib\smtplib.py", line 623, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, 'Error: \xc7\xeb\xca\xb9\xd3\xc3\xca\xda\xc8\xa8\xc2\xeb\xb5\xc7\xc2\xbc\xa1\xa3\xcf\xea\xc7\xe9\xc7\xeb\xbf\xb4: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256')
[Finished in 2.1s with exit code 1]
解决办法:点击上面开启POP3/SMTP服务页面的“生成授权码”,按要求操作成功后会得到一个16位的授权码,该授权码即为password。(上述代码中“******”处填入自己对应的信息即可,亲测有效。)
注:
(1)脚本别命名为email.py,否则会出错,具体参考:python 发送邮件及ImportError: No module named mime.text处理
(2)参考的教程中smtp为:smtplib.SMTP(smtp_server, 25),但我试了出现如下错误:
Traceback (most recent call last):
File "C:\Users\Desktop\0619\testemail.py", line 30, in <module>
smtp.connect( smtpserver )
File "D:\toolsforwork\Python27\lib\smtplib.py", line 318, in connect
(code, msg) = self.getreply()
File "D:\toolsforwork\Python27\lib\smtplib.py", line 369, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
[Finished in 60.3s with exit code 1]
改成下面这个就成功了。(QQ邮箱SMTP服务器地址:smtp.qq.com,ssl端口:465)
smtp = smtplib.SMTP_SSL(smtpserver,465)