python--Email提醒

发布日期:2019-04-28

发送邮箱的协议是STMP,python内置对SMTP支持,可以发送纯文本邮件,HTML邮件和带附件邮件。python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件

在使用前,先申请一个163邮箱,开启SMTP功能,采用网易的电子邮件服务器smtp.163.com

先构造纯文本邮件

from email.mime.text import MIMETextmsg = MIMEText("python爬虫运行异常","plain","utf-8")构造MIMEText对象需要3个参数邮件正文MIME的subtype,传入"plain"表示纯文本,最终的MIME就是“text/plain”设置编码格式,UTF-8编码保证多语言兼容性

下面是完整的代码

#coding:utf-8from email.header import Headerfrom email.mime.text import MIMETextfrom email.utils import parseaddr, formataddrimport smtplibdef _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, "utf-8").encode(), addr))#发件人地址from_addr = "xxxxxxxx@163.com"#邮箱密码password = "pass"#收件人地址to_addr = "xxxxxxxx@qq.com"#163网易邮箱服务器地址smtp_server = "smtp.163.com"#设置邮件信息msg = MIMEText("Python爬虫运行异常,异常信息为遇到HTTP 403", "plain", "utf-8")msg["From"] = _format_addr("一号爬虫 <%s>" % from_addr)msg["To"] = _format_addr("管理员 <%s>" % to_addr)msg["Subject"] = Header("一号爬虫运行状态", "utf-8").encode()#发送邮件server = smtplib.SMTP(smtp_server, 25)server.login(from_addr, password)server.sendmail(from_addr, [to_addr], msg.as_string())server.quit()