Python 发送邮件 email 模块、smtplib 模块
____tz_zs
SMTP
email 模塊:負(fù)則構(gòu)造郵件
smtplib 模塊:負(fù)則發(fā)送郵件
一、發(fā)送純文本郵件
from email.header import Header from email.mime.text import MIMEText import re import smtplib# 發(fā)送者、接收者 from_addr = 'xxxname@yyy.cn' password = 'zzz' to_addrs = 'xxxxto@foxmail.com' # 服務(wù)器、端口 smtp_host = 'smtp.exmail.qq.com' # SMTP 服務(wù)器主機 smtp_port = 465 # SMTP 服務(wù)器端口號# 創(chuàng)建 SMTP 對象 smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)#創(chuàng)建 MIMEText 對象 msg = MIMEText(_text="My email content, hello!", _subtype="plain", _charset="utf-8") # _text="郵件內(nèi)容" msg["Subject"] = Header(s="The title", charset="utf-8") # 標(biāo)題 msg["From"] = Header(s=from_addr) # 發(fā)送者 msg["To"] = Header(s=to_addrs) # 接收者 print(msg.as_string()) """ Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 Subject: =?utf-8?q?The_title?= From: xxxname@yyy.cn To: xxxx@foxmail.comTXkgZW1haWwgY29udGVudCwgaGVsbG/vvIE= """# 使用 SMTP 對象登錄、發(fā)送郵件 smtp_obj.login(user=from_addr, password=password) smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string()) smtp_obj.quit()MIMEText 對象
MIMEText 類是 MIMENonMultipart 類的子類,用于生成文本類型的郵件。郵件由標(biāo)題,發(fā)信人,收件人,郵件內(nèi)容,附件等構(gòu)成。
MIMEText(_text=“My email content, hello!”, _subtype=“plain”, _charset=“utf-8”)
參數(shù):
_text="" 為郵件內(nèi)容
_subtype=“plain” 設(shè)置文本格式。默認(rèn)為普通(plain)
_charset=“utf-8” 設(shè)置字符編碼格式,默認(rèn)為 us-ascii。從源碼可看出,當(dāng) _test 中包含 ascii 之外的字符,則將使用 utf-8 編碼
MIMENonMultipart源碼:
由源碼可知,此類及其子類不能調(diào)用 attach 函數(shù)添加額外的 part。
MIMENonMultipart 的子類有:
- MIMEImage: generating image/* type MIME documents.
- MIMEAudio: generating audio/* MIME documents.
- MIMEApplication: generating application/* MIME documents.
- MIMEMessage: representing message/* MIME documents.
- MIMEText: generating text/* type MIME documents.
sendmail()函數(shù)
sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
參數(shù):
from_addr: 發(fā)出郵件的地址
to_addrs: 一個list,包括要發(fā)送郵件的郵箱地址。也可以是一個字符串,這時會被當(dāng)成長度為1的list。
msg: 消息
二、發(fā)送HTML郵件
只需在創(chuàng)建 MIMEText 時,將 _subtype 設(shè)置為 “html”,則可發(fā)送 html 格式的郵件,其他步驟和發(fā)送純文本郵件一致。
如果要同時發(fā)送郵件給多個目標(biāo)郵箱,只需使用 list 包裹多個郵箱地址即可。需要注意的是,郵件的 “To” 字段部分需要的是字符串。
# 發(fā)送者、接收者 from_addr = 'xxxuser@yyy.cn' password = 'xxxpassword' # to_addrs = "zzz@gmail.com" to_addrs = 'zzz@foxmail.com'# 創(chuàng)建 SMTP 對象 smtp_host = 'smtp.exmail.qq.com' # SMTP 服務(wù)器主機 smtp_port = 465 # SMTP 服務(wù)器端口號 smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)str = """ <html><head><meta charset="UTF-8"></head><body><h1 align="center">html 標(biāo)題</h1><p>正文</p><br><a href="https://www.baidu.com/" target="_blank" title="點擊跳轉(zhuǎn)到百度">一個超鏈接</a><br></body> </html> """msg = MIMEText(_text=str, _subtype="html", _charset="utf-8") # _text="郵件內(nèi)容" msg["Subject"] = Header(s="發(fā)送 html 郵件", charset="utf-8") # 標(biāo)題 msg["From"] = Header(s=from_addr) # 發(fā)送者 msg["To"] = Header(s='; '.join(to_addrs)) # 接收者 print(msg.as_string()) """ Content-Type: text/html; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 Subject: =?utf-8?b?5Y+R6YCBIGh0bWwg6YKu5Lu2?= From: xxxuser@yyy.cn To: yyy@foxmail.com; yyy@gmail.comCjxodG1sPgogICAgPGhlYWQ+CiAgICAgICAgPG1ldGEgY2hhcnNldD0iVVRGLTgiPgogICAgPC9o ZWFkPgogICAgPGJvZHk+CiAgICA8aDEgYWxpZ249ImNlbnRlciI+aHRtbCDmoIfpopg8L2gxPgog ICAgPHA+5q2j5paHPC9wPgogICAgPGJyPgogICAgPGEgaHJlZj0iaHR0cHM6Ly93d3cuYmFpZHUu Y29tLyIgdGFyZ2V0PSJfYmxhbmsiIHRpdGxlPSLngrnlh7vot7PovazliLDnmb7luqYiPuS4gOS4 qui2hemTvuaOpTwvYT4KICAgIDxicj4KICAgIDwvYm9keT4KPC9odG1sPgo= """# 使用 SMTP 對象發(fā)送郵件 smtp_obj.login(user=from_addr, password=password) smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string()) smtp_obj.quit()三、發(fā)送帶附件的郵件
#!/usr/bin/python2.7 # -*- coding:utf-8 -*-""" @author: tz_zs """from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib# 發(fā)送者、接收者 from_addr = 'xxxsend@yyy.cn' password = '12345678' to_addrs = ['zzz@foxmail.com', 'zzz@gmail.com']# 創(chuàng)建 SMTP 對象 smtp_host = 'smtp.exmail.qq.com' # SMTP 服務(wù)器主機 smtp_port = 465 # SMTP 服務(wù)器端口號 smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)str = """ <html><head><meta charset="UTF-8"></head><body><h1 align="center">html 標(biāo)題</h1><p>正文</p><br><a href="https://www.baidu.com/" target="_blank" title="點擊跳轉(zhuǎn)到百度">一個超鏈接</a><br></body> </html> """msg = MIMEMultipart() msg["Subject"] = Header(s="發(fā)送帶附件的郵件", charset="utf-8") # 標(biāo)題 msg["From"] = Header(s=from_addr) # 發(fā)送者 msg["To"] = Header(s='; '.join(to_addrs)) # 接收者# 郵件正文 msg.attach(payload=MIMEText(_text="My email content, hello!", _subtype="plain", _charset="utf-8"))# 附件1 file_path = 'test.xls' att1 = MIMEText(_text=open(file_path, "rb").read(), _subtype="base64", _charset="utf-8") att1["Content-Type"] = "application/octet-stream" att1["Content-Disposition"] = "attachment; filename=%s" % file_path # filename 可以任意寫,寫什么名字,郵件中顯示什么名字。但是不要寫中文 msg.attach(payload=att1)# 附件2 file_path2 = 'a.png' att2 = MIMEText(_text=open(file_path2, "rb").read(), _subtype="base64", _charset="utf-8") att2["Content-Type"] = "application/octet-stream" att2["Content-Disposition"] = "attachment; filename=%s" % file_path2 # filename 可以任意寫,寫什么名字,郵件中顯示什么名字。但是不要寫中文 msg.attach(payload=att2)print(msg.as_string()) """ Content-Type: multipart/mixed; boundary="===============0753960931152521813==" MIME-Version: 1.0 Subject: =?utf-8?b?5Y+R6YCB5bim6ZmE5Lu255qE6YKu5Lu2?= From: xxxsend@yyy.cn To: zzz@foxmail.com; zzz@gmail.com--===============0753960931152521813== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64TXkgZW1haWwgY29udGVudCwgaGVsbG/vvIE=--===============0753960931152521813== Content-Type: text/base64; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Type: application/octet-stream Content-Disposition: attachment; filename=test.xls...... ...... ...... """# 使用 SMTP 對象發(fā)送郵件 smtp_obj.login(user=from_addr, password=password) smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string()) smtp_obj.quit()四、發(fā)送帶圖片展示的郵件
def send_img_mail(self):"""用于發(fā)送帶圖片的郵件"""# 發(fā)送者、接收者from_addr = 'xxx@yyy.cn'password = 'xyz'to_addrs = ["bbb@yyy.cn", "jjj@yyy.cn", "ccc@yyy.cn", ]# 創(chuàng)建 SMTP 對象smtp_host = 'smtp.exmail.qq.com' # SMTP 服務(wù)器主機smtp_port = 465 # SMTP 服務(wù)器端口號smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)msg = MIMEMultipart()msg["Subject"] = Header(s="發(fā)送帶圖片顯示的郵件", charset="utf-8") # 標(biāo)題msg["From"] = Header(s=from_addr) # 發(fā)送者msg["To"] = Header(s='; '.join(to_addrs)) # 接收者# 郵件正文message = """<html><head><meta charset="UTF-8"></head><body><h1 align="center">狀態(tài)監(jiān)控</h1><b>本郵件發(fā)送時間: %s</b><br><b>狀態(tài)報告: %s</b><h3>走勢:</h3><p><img src="cid:image1"></p></body></html>""" % (ToolDate.get_ymdhms_string(), self.df.to_html())# 創(chuàng)建 MIMEText ,并加入msgmsg.attach(payload=MIMEText(_text=message, _subtype="html", _charset="utf-8"))# 加載圖片內(nèi)容,創(chuàng)建 MIMEImagefp = open(self.path_output_open + "zusd_value_portfolio.png", 'rb')msgImage = MIMEImage(fp.read())fp.close()# 定義圖片 ID,與 HTML 文本中的引用id一致msgImage.add_header('Content-ID', '<image1>')# 加入msgmsg.attach(msgImage)# 使用 SMTP 對象發(fā)送郵件smtp_obj.login(user=from_addr, password=password)smtp_obj.sendmail(from_addr=from_addr, to_addrs=to_addrs, msg=msg.as_string())smtp_obj.quit()五、參考:
http://www.runoob.com/python/python-email.html
總結(jié)
以上是生活随笔為你收集整理的Python 发送邮件 email 模块、smtplib 模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现消消乐游戏_Python
- 下一篇: 浙江大学名录计算机学院博士,通知 | 关