作用:
监控爬虫脚本,出现异常或者正常结束时,给邮箱发送消息,自己好知道爬虫的进度
老样子,直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| # -*- coding: utf-8 -*- # @Author: Mehaei # @Date: 2019-08-27 18:12:38 # @Last Modified by: Mehaei # @Last Modified time: 2019-08-28 17:48:49
import smtplib from datetime import datetime
class ToEmail(object): def __init__(self, **kwargs): # 网易163邮箱 self.HOST = 'smtp.163.com' # 2> 配置服务的端口,默认的邮件端口是25. self.PORT = '465' # 第三方登录授权码 self.LICENSEKEY = '********' # 3> 指定发件人和收件人。 self.FROM = '**********@163.com' self.TO = '*********@163.com' # 4> 邮件标题 self.SUBJECT = kwargs.get("SUBJECT") or 'Email Message' # 重试次数 self.TOEMAILSUCESSFLAG = 5
def send(self, content):
if isinstance(content, list): content = "\n".join(content)
if not isinstance(content, str): content = str(content)
while self.TOEMAILSUCESSFLAG: try: # 创建邮件发送对象 # 普通的邮件发送形式 # smtp_obj = smtplib.SMTP() # 数据在传输过程中会被加密。 smtp_obj = smtplib.SMTP_SSL() # 需要进行发件人的认证,授权。 # smtp_obj就是一个第三方客户端对象 smtp_obj.connect(host=self.HOST, port=self.PORT) # 如果使用第三方客户端登录,要求使用授权码,不能使用真实密码,防止密码泄露。 smtp_obj.login(user=self.FROM, password=self.LICENSEKEY) # 发送邮件 msg = '\n'.join(['From: {}'.format(self.FROM), 'To: {}'.format(self.TO), 'Subject: {}'.format(self.SUBJECT), '', content]) smtp_obj.sendmail(from_addr=self.FROM, to_addrs=self.TO, msg=msg.encode('utf-8')) self.TOEMAILSUCESSFLAG = 0
except Exception as e: self.TOEMAILSUCESSFLAG -= 1
if __name__ == "__main__": toemail = ToEmail() toemail.send("test")
|
注意,使用邮箱发送邮件,需要登录邮箱 ,开启允许第三方登录客户端服务
163邮箱设置如下
设置 –> 客户端授权密码 –> 开启并设置授权密码
如有错误欢迎指出