使用python自动化发送邮件
1. smtplib
2. email
smtplib模块是对SMTP协议的封装,用于发送邮件;email模块用于构建邮件内容,支持以下3种形式的邮件
1. 纯文本
2. html
3. 带附件
首先来看下邮件的构建,对于一封邮件,需要指定发件人,收件人,主题,正文等内容,以最简单的纯文本邮件为例,构建方式如下
>>> from email.mime.text import MIMEText
>>> from email.header import Header
>>> subject = '主题'
>>> message = MIMEText('正文', 'plain', 'utf-8')
>>> message['From'] = Header("发件人", 'utf-8')
>>> message['To'] = Header("收件人", 'utf-8')
>>> message['Subject'] = Header(subject, 'utf-8')
对于html形式的邮件,只需要指定MIMEText的第二个参数为html即可,用法如下
>>> msg = '<p>正文</p>'
>>> message = MIMEText(msg, 'html', 'utf-8')
对于带附件的邮件,需要通过MIMEMultipart来创建邮件,用法如下
>>> from email.mime.multipart import MIMEMultipart
>>> message = MIMEMultipart()
>>> message.attach(MIMEText('正文', 'plain', 'utf-8'))
>>> attach = MIMEText(open('input.txt', 'rb').read(), 'base64', 'utf-8')
>>> attach["Content-Type"] = 'application/octet-stream'
>>> attach["Content-Disposition"] = 'attachment; filename="test.txt"'
>>> message.attach(attach)
创建好邮件之后,就可以通过SMTP来发送了,这里以QQ邮箱为例,首先需要开启QQ邮箱的SMTP服务器,然后生成授权码,图示如下
用QQ邮箱发送邮件的代码如下
>>> import smtplib
>>> from email.mime.text import MIMEText
>>> from email.header import Header
>>> message = MIMEText('正文', 'plain', 'utf-8')
>>> message['From'] = Header("发件人", 'utf-8')
>>> message['To'] = Header("收件人", 'utf-8')
>>> message['Subject'] = Header('主题', 'utf-8')
>>> server=smtplib.SMTP_SSL("smtp.qq.com", 465)
>>> server.login('xxxxxxxx@qq.com', 'dvyybvbwpnnbbdaj')
>>> server.sendmail('xxxxxxxx@qq.com', 'xxxxxxxx@qq.com' , message.as_string())
对于需要定期发送,且内容较为固定的邮件,通过自动化可以大大减少工作量,比如通过python监控磁盘空间,当使用率超过80%时,自动向运维人员发送邮件,以提醒备份和清理磁盘。
赞 (0)