from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib def _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() Email起到提醒作用,当爬虫过程中遇到异常或者服务器遇到问题,可以通过Email及时向自己报告。 发送邮件的协议是STMP,python内置对SMTP的支持,可以发送纯文本邮件、html邮件以及带附件的邮件。 python对SMTP的支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。 from email.mime.text import MIMEText msg = MIMEText(\'Python爬虫运行异常,异常信息为遇到HTTP 403\', \'plain\', \'utf-8\') 构造MIMEText对象时需要三个参数 邮件正文,\'Python爬虫运行异常,异常信息为遇到HTTP 403\' MIMEL的subtype,\'plain\'表示纯文本 编码格式,\'utf-8\'
import smtplib from email.mime.text import MIMEText from email.header import Header # 第三方 SMTP 服务 mail_host="smtp.XXX.com" #设置服务器 mail_user="XXXX" #用户名 mail_pass="XXXXXX" #口令 sender = \'from@runoob.com\' receivers = [\'429240967@qq.com\'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 message = MIMEText(\'Python 邮件发送测试...\', \'plain\', \'utf-8\') message[\'From\'] = Header("菜鸟教程", \'utf-8\') message[\'To\'] = Header("测试", \'utf-8\') subject = \'Python SMTP 邮件测试\' message[\'Subject\'] = Header(subject, \'utf-8\') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print "邮件发送成功" except smtplib.SMTPException: print "Error: 无法发送邮件"