|
| 1 | +# _*_ coding: utf-8 _*_ |
| 2 | + |
| 3 | +""" |
| 4 | +python发送邮件 |
| 5 | +""" |
| 6 | + |
| 7 | +import smtplib |
| 8 | +from email.header import Header |
| 9 | +from email.mime.text import MIMEText |
| 10 | +from email.mime.image import MIMEImage |
| 11 | +from email.mime.multipart import MIMEMultipart |
| 12 | + |
| 13 | +# 第三方 SMTP 服务(以腾讯企业邮件为例) |
| 14 | +mail_host = "smtp.exmail.qq.com" |
| 15 | +mail_user = "from@from.com.cn" |
| 16 | +mail_pass = "pwd" |
| 17 | +mail_sender = mail_user |
| 18 | +mail_receivers = ["to@to.com", "to@qq.com"] |
| 19 | + |
| 20 | +# 设置邮件格式、内容等 -- 普通格式 ================================================ |
| 21 | +msg_plain = "邮件内容" |
| 22 | +message = MIMEText("邮件内容", "plain", "utf-8") |
| 23 | + |
| 24 | +# 设置邮件格式、内容等 -- HTML格式 =============================================== |
| 25 | +msg_html = """ |
| 26 | +<p>Python 邮件发送测试...</p> |
| 27 | +<p><a href="http://www.runoob.com">这是一个链接</a></p> |
| 28 | +<table border="1"> |
| 29 | + <tr><th>Month</th><th>Savings</th></tr> |
| 30 | + <tr><td>January</td><td>$100</td></tr> |
| 31 | + <tr><td>February</td><td>$80</td></tr> |
| 32 | +</table> |
| 33 | +""" |
| 34 | +message = MIMEText(msg_html, "html", "utf-8") |
| 35 | + |
| 36 | +# 设置邮件格式、内容等 -- HTML格式(带有图片和附件)================================== |
| 37 | +msg_html = """ |
| 38 | +<p>Python 邮件发送测试...</p> |
| 39 | +<p><a href="http://www.runoob.com">这是一个链接</a></p> |
| 40 | +<p>图片演示:</p> |
| 41 | +<p><img src="cid:image_id_1"></p> |
| 42 | +""" |
| 43 | +msg_content = MIMEText(msg_html, "html", "utf-8") |
| 44 | +msg_image = MIMEImage(open("test.png", "rb").read()) |
| 45 | +msg_image.add_header("Content-ID", "<image_id_1>") |
| 46 | + |
| 47 | +msg_file = MIMEText(open("test.csv", "rb").read(), "base64", "utf-8") |
| 48 | +msg_file["Content-Type"] = "application/octet-stream" |
| 49 | +msg_file["Content-Disposition"] = "attachment; filename=\"test.csv\"" |
| 50 | + |
| 51 | +message = MIMEMultipart("related") |
| 52 | +message.attach(msg_content) |
| 53 | +message.attach(msg_image) |
| 54 | +message.attach(msg_file) |
| 55 | +# ============================================================================== |
| 56 | + |
| 57 | +# 设置邮件的收发件、标题等 |
| 58 | +message["From"] = mail_sender |
| 59 | +message["To"] = ";".join(mail_receivers) |
| 60 | +message["Subject"] = Header("邮件标题", "utf-8") |
| 61 | + |
| 62 | +try: |
| 63 | + # 登录,并发送邮件 |
| 64 | + smtpObj = smtplib.SMTP() |
| 65 | + smtpObj.connect(mail_host, 25) |
| 66 | + smtpObj.login(mail_user, mail_pass) |
| 67 | + smtpObj.sendmail(mail_sender, mail_receivers, message.as_string()) |
| 68 | + print("success") |
| 69 | +except smtplib.SMTPException as excep: |
| 70 | + print("error", excep) |
0 commit comments