5.3 发送报告
5.3.1 SMTP协议发送邮件
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib
和email
两个模块,email
负责构造邮件,smtplib
负责发送邮件:
#!/usr/bin/python3
from email.mime.text import MIMEText
import smtplib
import getpass
from_addr = 'liugz@wanho.net'
password = getpass.getpass('Password: ')
to_addr = from_addr
smtp_server = 'smtp.exmail.qq.com'
msg = MIMEText('hello python email.', 'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'python mail test.'
server = smtplib.SMTP(smtp_server, 25)
# server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
使用email的MIMEText对象构造邮件,分别包括正文,发送者,接收者,主题等。然后使用smtplib的SMTP类构造一个对象,负责登录到smtp服务器,并发送此邮件。
结果将收到此邮件:
如果需要发送附件,则引入:
from email.mime.multipart import MIMEMultipart
然后构造一个带附件的邮件对象并发送:
new_msg = MIMEMultipart()
new_msg['Subject'] = 'Python发送带附件的邮件'
new_msg['From'] = from_addr
new_msg['To'] = to_addr
att = MIMEText(open('test.conf').read())
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="test.conf"'
new_msg.attach(att)
结果为:
对于部分邮箱,需要开启SMTP服务,获取授权码,以便程序能够使用smtp服务发送邮件,这时,输入的密码为授权码。
5.3.2 使用开源的yagmail发送邮件
yagmail是一个可以发送邮件的第三方包,安装如下:
pip install yagmail
使用yagmail发送邮件如下:
import yagmail
from_addr = 'liugz@wanho.net'
password = getpass.getpass('Password: ')
to_addr = from_addr
smtp_server = 'smtp.exmail.qq.com'
mail = yagmail.SMTP(user=from_addr, password=password, host=smtp_server)
mail.send(
to=to_addr,
subject='python mail test.',
contents='hello python email.',
attachments='test.conf')
print('发送成功')