美文网首页officePython
Python 使用smtplib包自动用QQ邮箱通过SMTP协议

Python 使用smtplib包自动用QQ邮箱通过SMTP协议

作者: 小菜鸡 | 来源:发表于2021-01-16 12:10 被阅读0次

Python调用smtplib包使用QQ邮箱进行邮件的发送

写了一个爬虫的脚本,想要每隔一段时间通知我一下爬取的情况,包括目前的进度以及是否遇错重试(retrying.retry())了,就想到了写个脚本通过QQ自动发送邮件通知自己哈(当然调用微信发消息也可以,那就是另外的一个坑了)

首先是notify_me.py:

import smtplib
import time
from email.header import Header
from email.mime.text import MIMEText


def report(reports: str):
    '''
    发送提醒邮件
    :param reports: 邮件内容
    :return:
    '''
    # QQ邮件的SMTP服务器
    mail_host = "smtp.qq.com"
    # 发信人
    mail_sender = "*********@qq.com"
    # 授权码
    mail_authorization_code = "**************"
    # 收件人
    mail_receivers = ["**********@qq.com"]
    # 构造邮件内容
    message = MIMEText(reports, 'plain', 'utf-8')
    message['From'] = Header("Crawler<{}>".format(mail_sender), 'utf-8')  # 发送者
    message['To'] = Header("Master", 'utf-8')  # 接收者
    # 邮件显示的主题
    subject = 'Crawler new status report'
    message['Subject'] = Header(subject, 'utf-8')
    stp = smtplib.SMTP()
    # QQ邮箱的SMTP的ssl端口是587
    stp.connect(mail_host, 587)
    # 使用授权码登录
    stp.login(mail_sender, mail_authorization_code)
    stp.sendmail(mail_sender, mail_receivers, message.as_string())
    print("邮件发送成功@", time.asctime())
    stp.quit()


def main():
    reports = 'This is the test email from the script.'
    report(reports)


if __name__ == '__main__':
    main()

这里面很重要的一个东西就是QQ邮箱的 授权码,拿到这个才能够做认证

获取QQ邮箱的授权码

1、首先登陆QQ邮箱,之后到 设置>账户栏

设置>账户

2、翻到最底下,有一个SMTP的设置


SMTP设置

3、点击开启按钮,会提示用关联的手机号发一个开启的短信


发送开启短信

4、发送短信之后,点击“我已发送”,就会得到授权码了


授权码

直接运行notify_me.py测试一下,收到的邮件:

测试结果

最后放到爬虫里面:

from ***.notify_me import report
...
# retry 20 times, with interval 10 seconds after each fail
@retry(stop_max_attempt_number=100, wait_fixed=10000)
def main():
    reports = process()
    report(reports)
...

另外想使用163发送的见参考链接

参考:

https://zhuanlan.zhihu.com/p/89868804
https://www.runoob.com/python/python-email.html

相关文章

网友评论

    本文标题:Python 使用smtplib包自动用QQ邮箱通过SMTP协议

    本文链接:https://www.haomeiwen.com/subject/ourgaktx.html