标签:osi read 你好 企业 文字 邮件 图片 主题 span
1、导入所需要的模块
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.header import Header
2、设置smtplib所需的参数
# 下面的发件人,收件人是用于邮件传输的。 smtpserver = ‘exmail.qq.com‘ username = ‘XXX@daydaycook.com‘ password = ‘***‘ sender = ‘XXX@daydaycook.com‘ # receiver=‘XXX@126.com‘ 单个收件人 # 多个收件人 receiver = [‘XXX@daydaycook.com‘, ‘***g@daydaycook.com‘]
3、构造邮件对象MIMEMultipart对象
subject = ‘中文标题‘ subject = Header(subject, ‘utf-8‘).encode() # 下面的主题,发件人,收件人,日期是显示在邮件页面上的。
# MIMEMultipart主要有三种类型:mixed、alternative、related msg = MIMEMultipart(‘mixed‘) msg[‘Subject‘] = subject msg[‘From‘] = ‘XXX@daydaycook.com <XXX@daydaycook.com>‘ # msg[‘To‘] = ‘XXX@126.com‘ # 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串 msg[‘To‘] = ";".join(receiver) # msg[‘Date‘]=‘2012-3-16‘
4、构造文字内容
text = "嗨!\n你好吗?\nHere is the link you wanted:\nhttp://www.baidu.com" text_plain = MIMEText(text, ‘plain‘, ‘utf-8‘) msg.attach(text_plain)
5、构造图片附件
send_image_file = open(r‘/Users/ddcuser/Downloads/true.jpeg‘, ‘rb‘).read() image = MIMEImage(send_image_file) image.add_header(‘Content-ID‘, ‘<image1>‘) image["Content-Disposition"] = ‘attachment; filename="testimage.png"‘ msg.attach(image)
6、构造html附件
# 发送正文中的图片:由于包含未被许可的信息,网易邮箱定义为垃圾邮件,报554 DT:SPM :<p><img src="cid:image1"></p> html = """ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> </p> </body> </html> """ text_html = MIMEText(html, ‘html‘, ‘utf-8‘) text_html["Content-Disposition"] = ‘attachment; filename="text_html.html"‘ msg.attach(text_html)
7、构造压缩文件zip附件
sendfile = open(r‘/Users/ddcuser/Downloads/20191211160425_sendCredit_result.zip‘, ‘rb‘).read() text_att = MIMEText(sendfile, ‘base64‘, ‘utf-8‘) text_att["Content-Type"] = ‘application/octet-stream‘ # 附件可以重命名成aaa.zip text_att.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘aaa.zip‘) msg.attach(text_att)
8、构造txt附件
sendfile = open(r‘/Users/ddcuser/Downloads/20191211160425_sendCredit_result.txt‘, ‘rb‘).read() text_att = MIMEText(sendfile, ‘base64‘, ‘utf-8‘) text_att["Content-Type"] = ‘application/octet-stream‘ # 附件可以重命名成aaa.txt text_att.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘aaa.txt‘) msg.attach(text_att)
9、构造xls附件
sendfile = open(r‘/Users/ddcuser/Downloads/20191211160425_sendCredit_result.xls‘, ‘rb‘).read() text_att = MIMEText(sendfile, ‘base64‘, ‘utf-8‘) text_att["Content-Type"] = ‘application/octet-stream‘ # 附件可以重命名成aaa.xls text_att.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘aaa.xls‘) msg.attach(text_att)
10、发送邮件
smtp = smtplib.SMTP() # 发件人是腾讯企业邮箱,如果用其他邮箱需要修改参数 smtp.connect(‘smtp.exmail.qq.com‘) smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
标签:osi read 你好 企业 文字 邮件 图片 主题 span
原文地址:https://www.cnblogs.com/lilyo/p/12024305.html