1 import smtplib 2 from email.mime.text import MIMEText 3 from email.mime.multipart import MIMEMultipart 4 from email.mime.image import MIMEImage 5 from email.header import Header 6 7 #第三方SMTP服务器 8 mail_host = "mail.163.com" #服务器 9 mail_user = "[email protected]" 10 mail_pass = "123456" 11 sender = "[email protected]" 12 receivers = ["[email protected]","[email protected]"] 13 14 message = MIMEMultipart() 15 message["From"] = sender 16 message["To"] = ";".join(receivers) 17 message["Subject"] = "这是邮件主题(SMTP测试)" 18 #邮件正文内容: 19 message.attach(MIMEText( 20 """ 21 <p>这是正文:图片及附件发送测试</p> 22 <p>图片演示:</p> 23 <p><img src='cid:image1'</p> 24 """, 25 "html", 26 "utf-8", 27 )) 28 #指定图片路径,如果当前目录图片,直接写图片名即可 29 fp = open(r"D:\temp\2.jpg","rb") 30 msgImage = MIMEImage(fp.read()) 31 fp.close() 32 #定义图片ID,在HTML文本中引用 33 msgImage.add_header("Content-ID","<image1>") 34 message.attach(msgImage) 35 #添加附件1 36 att1 = MIMEText(open(r"D:\temp\test1.txt","rb").read(),"base64","utf-8") 37 att1["Content-Type"] = "application/octet-stream" 38 #这里的filename写什么,邮件中显示的是什么 39 att1["Content-Disposition"] = 'attachment;filename="mytest.txt"' 40 message.attach(att1) 41 #添加附件2 42 att2 = MIMEText(open(r"D:\temp\测试.txt","rb").read(),"base64","utf-8") 43 att2["Content-Type"] = "application/octet-stream" 44 #这里的filename写什么,邮件中显示的是什么 45 att2.add_header("Content-Disposition","attachment",filename=("gbk","","我的测试.txt")) 46 message.attach(att2) 47 48 try: 49 smtpObj = smtplib.SMTP() 50 smtpObj.connect(mail_host,25) 51 smtpObj.login(mail_user,mail_pass) 52 smtpObj.sendmail(sender,receivers,message.as_string()) 53 print("邮件发送成功") 54 except smtplib.SMTPException as e: 55 print(f"邮件发送失败,错误原因:{e}")
标签:Content,发送,mail,附件,import,message,com,邮件 From: https://www.cnblogs.com/donfag/p/17707004.html