日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 发送邮件 email 模块、smtplib 模块

發布時間:2024/1/1 python 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 发送邮件 email 模块、smtplib 模块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

____tz_zs

SMTP

email 模塊:負則構造郵件
smtplib 模塊:負則發送郵件

一、發送純文本郵件

from email.header import Header from email.mime.text import MIMEText import re import smtplib# 發送者、接收者 from_addr = 'xxxname@yyy.cn' password = 'zzz' to_addrs = 'xxxxto@foxmail.com' # 服務器、端口 smtp_host = 'smtp.exmail.qq.com' # SMTP 服務器主機 smtp_port = 465 # SMTP 服務器端口號# 創建 SMTP 對象 smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)#創建 MIMEText 對象 msg = MIMEText(_text="My email content, hello!", _subtype="plain", _charset="utf-8") # _text="郵件內容" msg["Subject"] = Header(s="The title", charset="utf-8") # 標題 msg["From"] = Header(s=from_addr) # 發送者 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 對象登錄、發送郵件 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 類的子類,用于生成文本類型的郵件。郵件由標題,發信人,收件人,郵件內容,附件等構成。
MIMEText(_text=“My email content, hello!”, _subtype=“plain”, _charset=“utf-8”)
參數:

_text="" 為郵件內容
_subtype=“plain” 設置文本格式。默認為普通(plain)
_charset=“utf-8” 設置字符編碼格式,默認為 us-ascii。從源碼可看出,當 _test 中包含 ascii 之外的字符,則將使用 utf-8 編碼

MIMENonMultipart源碼:
由源碼可知,此類及其子類不能調用 attach 函數添加額外的 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.
class MIMEText(MIMENonMultipart):"""Class for generating text/* type MIME documents."""def __init__(self, _text, _subtype='plain', _charset=None):"""Create a text/* type MIME document._text is the string for this message object._subtype is the MIME sub content type, defaulting to "plain"._charset is the character set parameter added to the Content-Typeheader. This defaults to "us-ascii". Note that as a side-effect, theContent-Transfer-Encoding header will also be set."""# If no _charset was specified, check to see if there are non-ascii# characters present. If not, use 'us-ascii', otherwise use utf-8.# XXX: This can be removed once #7304 is fixed.if _charset is None:try:_text.encode('us-ascii')_charset = 'us-ascii'except UnicodeEncodeError:_charset = 'utf-8'if isinstance(_charset, Charset):_charset = str(_charset)MIMENonMultipart.__init__(self, 'text', _subtype,**{'charset': _charset})self.set_payload(_text, _charset)class MIMENonMultipart(MIMEBase):"""Base class for MIME non-multipart type messages."""def attach(self, payload):# The public API prohibits attaching multiple subparts to MIMEBase# derived subtypes since none of them are, by definition, of content# type multipart/*raise errors.MultipartConversionError('Cannot attach additional subparts to non-multipart/*')

sendmail()函數

sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
參數:
from_addr: 發出郵件的地址
to_addrs: 一個list,包括要發送郵件的郵箱地址。也可以是一個字符串,這時會被當成長度為1的list。
msg: 消息

二、發送HTML郵件

只需在創建 MIMEText 時,將 _subtype 設置為 “html”,則可發送 html 格式的郵件,其他步驟和發送純文本郵件一致。

如果要同時發送郵件給多個目標郵箱,只需使用 list 包裹多個郵箱地址即可。需要注意的是,郵件的 “To” 字段部分需要的是字符串。

# 發送者、接收者 from_addr = 'xxxuser@yyy.cn' password = 'xxxpassword' # to_addrs = "zzz@gmail.com" to_addrs = 'zzz@foxmail.com'# 創建 SMTP 對象 smtp_host = 'smtp.exmail.qq.com' # SMTP 服務器主機 smtp_port = 465 # SMTP 服務器端口號 smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)str = """ <html><head><meta charset="UTF-8"></head><body><h1 align="center">html 標題</h1><p>正文</p><br><a href="https://www.baidu.com/" target="_blank" title="點擊跳轉到百度">一個超鏈接</a><br></body> </html> """msg = MIMEText(_text=str, _subtype="html", _charset="utf-8") # _text="郵件內容" msg["Subject"] = Header(s="發送 html 郵件", charset="utf-8") # 標題 msg["From"] = Header(s=from_addr) # 發送者 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 對象發送郵件 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()

三、發送帶附件的郵件

#!/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# 發送者、接收者 from_addr = 'xxxsend@yyy.cn' password = '12345678' to_addrs = ['zzz@foxmail.com', 'zzz@gmail.com']# 創建 SMTP 對象 smtp_host = 'smtp.exmail.qq.com' # SMTP 服務器主機 smtp_port = 465 # SMTP 服務器端口號 smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)str = """ <html><head><meta charset="UTF-8"></head><body><h1 align="center">html 標題</h1><p>正文</p><br><a href="https://www.baidu.com/" target="_blank" title="點擊跳轉到百度">一個超鏈接</a><br></body> </html> """msg = MIMEMultipart() msg["Subject"] = Header(s="發送帶附件的郵件", charset="utf-8") # 標題 msg["From"] = Header(s=from_addr) # 發送者 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 對象發送郵件 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()

四、發送帶圖片展示的郵件

def send_img_mail(self):"""用于發送帶圖片的郵件"""# 發送者、接收者from_addr = 'xxx@yyy.cn'password = 'xyz'to_addrs = ["bbb@yyy.cn", "jjj@yyy.cn", "ccc@yyy.cn", ]# 創建 SMTP 對象smtp_host = 'smtp.exmail.qq.com' # SMTP 服務器主機smtp_port = 465 # SMTP 服務器端口號smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)msg = MIMEMultipart()msg["Subject"] = Header(s="發送帶圖片顯示的郵件", charset="utf-8") # 標題msg["From"] = Header(s=from_addr) # 發送者msg["To"] = Header(s='; '.join(to_addrs)) # 接收者# 郵件正文message = """<html><head><meta charset="UTF-8"></head><body><h1 align="center">狀態監控</h1><b>本郵件發送時間: %s</b><br><b>狀態報告: %s</b><h3>走勢:</h3><p><img src="cid:image1"></p></body></html>""" % (ToolDate.get_ymdhms_string(), self.df.to_html())# 創建 MIMEText ,并加入msgmsg.attach(payload=MIMEText(_text=message, _subtype="html", _charset="utf-8"))# 加載圖片內容,創建 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 對象發送郵件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

總結

以上是生活随笔為你收集整理的Python 发送邮件 email 模块、smtplib 模块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。