SMPT(Simple Mail Transfer Protocol)简单邮件传输协议,是一组由源地址到目的地址传送邮件的规则,可以控制信件的中转方式。Python的smptlib模块提供了简单的API用来实现发送邮件的功能,它对SMPT进行了简单的封装。
一、python自带的发送邮件功能
1、发送邮件正文
1 import smtplib 2 from email.mime.text import MIMEText 3 from email.header import Header 4 5 # 发送邮件主题 6 subject = ‘hello my dear;‘ 7 8 # 编写HTML类型的邮件正文 9 msg = MIMEText(‘<html><h1>helloMMAMAMAAMAM</h1></html>‘, ‘html‘, ‘utf-8‘) 10 msg[‘Subject‘] = Header(subject, ‘utf-8‘) 11 msg[‘from‘] = ‘[email protected]‘ 12 msg[‘to‘] = ‘[email protected]‘ 13 14 # 发送邮件 15 smtp = smtplib.SMTP() 16 smtp.connect("smtp.126.com") 17 smtp.login("[email protected]", "19970507zudangli") 18 smtp.sendmail("[email protected]", "[email protected]", msg.as_string()) 19 smtp.quit()
,
email模块下面的MIMEText类,定义发送邮件的正文、格式,以及编码,Header类定义邮件的主题和编码类型
smptlib模块用于发送邮件的。connect()方法指定连接的邮箱服务;login()方法指定登录邮箱的账号和密码;sendmail()方法指定发件人、收件人,以及邮件的正文;quit()方法用于关闭邮件服务器的连接。
2、发送带附件的邮件
1 import smtplib 2 from email.mime.text import MIMEText 3 from email.mime.multipart import MIMEMultipart 4 5 # 邮件主题 6 subject = ‘python带附件的发送邮件‘ 7 # 发送的附件 8 with open(‘test.txt‘, ‘rb‘) as f: 9 send_att = f.read() 10 11 att = MIMEText(send_att, ‘text‘, ‘utf-8‘) 12 att["Content-Type"] = ‘application/octet-stream‘ 13 att["Content-Disposition"] = ‘attachment; filename="I am attachment.txt"‘ 14 15 16 msg = MIMEMultipart() 17 msg[‘Subject‘] = subject 18 msg[‘from‘] = ‘[email protected]‘ 19 msg[‘to‘] = ‘[email protected]‘ 20 msg.attach(att) 21 22 # 发送邮件 23 smtp = smtplib.SMTP() 24 smtp.connect("smtp.126.com") 25 smtp.login("[email protected]", "19970507zudangli") 26 smtp.sendmail("[email protected]", "[email protected]", msg.as_string()) 27 smtp.quit()
首先,读取附件的内容。通过MIMEText类,定义发送邮件的正文、格式,以及编码;
- Content-Type指定附件内容类型;
- application/octet-stream表示二进制流;
- Content-Disposition指定显示附件的文件
然后,使用MIMEMultipart类定义邮件的主题,attach()指定附件信息。
最后,通过smtplib模块发送邮件。
二、用yagmail发送邮件
yagmail是Python的一个第三方库,GitHub项目地址:https://github.com/kootenpv/yagmail
安装命令:pip install yagmail
1 import yagmail 2 3 # 连接邮箱服务器 4 yag = yagmail.SMTP(user="[email protected]", password="19970507zudangli", host="smtp.126.com") 5 6 # 邮件正文 7 contents = [‘This is the body,and here is just text http://somedomain/image.png‘, ‘You can find an audio file attached.‘] 8 9 # 发送邮件 10 yag.send(‘[email protected]‘, ‘subject‘, contents)
如果想给多个用户发送邮件,只需要把收件人放到一个list中即可
yag.send([‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘], ‘subject‘, contents)
如果想发送带附件的邮件,只需要指定本地附件的路径即可。
1 yag.send([‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘], ‘subject‘, contents, ["C://Users//zudl//Pictures//timg.jpg","F://秒通OApython//formal.py"])
原文地址:https://www.cnblogs.com/pegawayatstudying/p/12368201.html
时间: 2024-11-02 02:46:18