用python連接SMTP的TLS(587端口)發郵件
2020年3月6日 / 263次閱讀 / Last Modified 2020年3月6日
Email
python標准庫中的smtplib模塊,給我們提供了一組連接SMTP服務器發送郵件的接口。連接SMTP服務器未加密的25號端口,使用smtplib.SMTP接口;連接SMTP服務器SSL加密的465端口,使用smtplib.SMTP_SSL接口;本文記錄如何連接TLS的587端口。
我只知道TLS是SSL的升級版,升級后恐怕有一些加密認證流程不一樣了,所以python並沒有升級SSL這個接口來支持TLS。
連接SMTP服務器的TLS 587端口,同樣是使用smtplib.SMTP接口,只是需要填入587端口號(這是標准端口號)去連接。然后調用starttls接口,開啟TLS之旅。下面是測試代碼:
import smtplib from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr msg_str = 'this is a test email sending by python' msg = MIMEText(msg_str, 'plain', 'utf-8') msg['From'] = 'from@qq.com' msg['To'] = 'to@qq.com' msg['Subject'] = Header('python email test', 'utf-8').encode() smtp = smtplib.SMTP('smtp.qq.com',587) smtp.set_debuglevel(2) smtp.starttls() smtp.login('from@qq.com', 'password') smtp.sendmail('from@qq.com', 'to@qq.com', msg.as_string()) smtp.quit()
高亮的15行就是關鍵,調用starttls接口后,后面代碼跟SMTP服務器的交換,就全部是在TLS加密保護之下。
我測試了不調用starttls接口,連接587端口
python發郵件(帶認證,587端口)
使用python發郵件(帶認證,587端口):
vi mail.py
#!/usr/bin/python
-- coding:UTF-8 --
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtpserver='smtp.ming.com'
username='ming.yang@ming.com'
password='xxxxxx'
sender='ming.yang@ming.com'
receiver = ['zhi.yang@ming.com','zhi2.yang@ming.com']
subject='aa'
msg=MIMEMultipart('mixed')
msg['Subject']=subject
msg['From']='ming.yang@ming.com'
msg['To']=";".join(receiver)
text="Hi"
text_plain=MIMEText(text,'plain','utf-8')
msg.attach(text_plain)
smtp=smtplib.SMTP()
smtp.connect('smtp.ming.com',587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
:wq
執行
python mail.py
簡單郵件傳輸協議(SMTP)是一種協議,用於在郵件服務器之間發送電子郵件和路由電子郵件。
Python提供smtplib
模塊,該模塊定義了一個SMTP客戶端會話對象,可用於使用SMTP或ESMTP偵聽器守護程序向任何互聯網機器發送郵件。
這是一個簡單的語法,用來創建一個SMTP對象,稍后將演示如何用它來發送電子郵件 -
import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
這里是上面語法的參數細節 -
-
host - 這是運行SMTP服務器的主機。可以指定主機的IP地址或類似
yiibai.com
的域名。這是一個可選參數。 -
port - 如果提供主機參數,則需要指定SMTP服務器正在偵聽的端口。通常這個端口默認值是:
25
。 -
local_hostname - 如果SMTP服務器在本地計算機上運行,那么可以只指定
localhost
選項。
SMTP對象有一個sendmail
的實例方法,該方法通常用於執行郵件發送的工作。它需要三個參數 -
-
sender - 具有發件人地址的字符串。
-
receivers - 字符串列表,每個收件人一個。
-
message - 作為格式如在各種RFC中指定的字符串。
1.使用Python發送純文本電子郵件
示例
以下是使用Python腳本發送一封電子郵件的簡單方法 -
#!/usr/bin/python3import smtplib sender = 'from@fromdomain.com'receivers = ['to@todomain.com'] message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. """try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
在這里,已經發送了一封基本的電子郵件,使用三重引號,請注意正確格式化標題。一封電子郵件需要一個From
,To
和一個Subject
標題,與電子郵件的正文與空白行分開。
要發送郵件,使用smtpObj
連接到本地機器上的SMTP服務器。 然后使用sendmail
方法以及消息,從地址和目標地址作為參數(即使來自和地址在電子郵件本身內,這些並不總是用於路由郵件)。
如果沒有在本地計算機上運行SMTP服務器,則可以使用smtplib
客戶端與遠程SMTP服務器進行通信。除非您使用網絡郵件服務(如gmail或Yahoo! Mail),否則您的電子郵件提供商必須向您提供可以提供的郵件服務器詳細信息。以騰訊QQ郵箱為例,具體如下:
mail = smtplib.SMTP('smtp.qq.com', 587) # 端口465或587
2.使用Python發送HTML電子郵件
當使用Python發送郵件信息時,所有內容都被視為簡單文本。 即使在短信中包含HTML標簽,它也將顯示為簡單的文本,HTML標簽將不會根據HTML語法進行格式化。 但是,Python提供了將HTML消息作為HTML消息發送的選項。
發送電子郵件時,可以指定一個Mime版本,內容類型和發送HTML電子郵件的字符集。
以下是將HTML內容作為電子郵件發送的示例 -
#!/usr/bin/python3import smtplib message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> """try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
3.發送附件作為電子郵件
要發送具有混合內容的電子郵件,需要將Content-type標題設置為multipart / mixed。 然后,可以在邊界內指定文本和附件部分。
一個邊界以兩個連字符開始,后跟一個唯一的編號,不能出現在電子郵件的消息部分。 表示電子郵件最終部分的最后一個邊界也必須以兩個連字符結尾。
所附的文件應該用包(“m”)功能編碼,以便在傳輸之前具有基本的64編碼。
4.發送示例
首先我們要知道用python代理登錄qq郵箱發郵件,是需要更改自己qq郵箱設置的。在這里大家需要做兩件事情:郵箱開啟SMTP功能 、獲得授權碼。之后我們來看看如何更改模板代碼,實現使用Python登錄QQ郵箱發送QQ郵件。
注意:也可以使用其他服務商的 SMTP 訪問(QQ、網易、Gmail等)。
使用QQ郵件發送郵件之前如何設置授權碼,參考:
http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
4.1.發送一純文本郵件到指定郵件
#! /usr/bin/env python#coding=utf-8from email.mime.text import MIMETextfrom email.header import Headerfrom smtplib import SMTP_SSL#qq郵箱smtp服務器host_server = 'smtp.qq.com'#sender_qq為發件人的qq號碼sender_qq = '7697****@qq.com'#pwd為qq郵箱的授權碼pwd = '****kenbb***' ## xh**********bdc#發件人的郵箱sender_qq_mail = '7697****@qq.com'#收件人郵箱receiver = 'yiibai.com@gmail.com'#郵件的正文內容mail_content = '你好,這是使用python登錄qq郵箱發郵件的測試'#郵件標題mail_title = 'Maxsu的郵件'#ssl登錄smtp = SMTP_SSL(host_server)#set_debuglevel()是用來調試的。參數值為1表示開啟調試模式,參數值為0關閉調試模式smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender_qq, pwd) msg = MIMEText(mail_content, "plain", 'utf-8') msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_qq_mail msg["To"] = receiver smtp.sendmail(sender_qq_mail, receiver, msg.as_string()) smtp.quit()
執行上面代碼后,登錄接收郵件的郵件帳號,這里接收郵件的賬號為:yiibai.com@gmail.com
,登錄 http://gmail.com 應該會看到有接收到郵件如下 -
注意:有時可能被認為是垃圾郵件,如果沒有找到可從“垃圾郵件”查找一下。
4.2.給多個人發送郵件
#! /usr/bin/env python#coding=utf-8from email.mime.text import MIMETextfrom email.header import Headerfrom smtplib import SMTP_SSL#qq郵箱smtp服務器host_server = 'smtp.qq.com'#sender_qq為發件人的qq號碼sender_qq = '7697****@qq.com'#pwd為qq郵箱的授權碼pwd = 'h**********bdc' ## h**********bdc#發件人的郵箱sender_qq_mail = '7697****@qq.com'#收件人郵箱receivers = ['yiibai.com@gmail.com','****su@gmail.com']#郵件的正文內容mail_content = '你好,這是使用python登錄qq郵箱發郵件的測試'#郵件標題mail_title = 'Maxsu的郵件'#ssl登錄smtp = SMTP_SSL(host_server)#set_debuglevel()是用來調試的。參數值為1表示開啟調試模式,參數值為0關閉調試模式smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender_qq, pwd) msg = MIMEText(mail_content, "plain", 'utf-8') msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_qq_mail msg["To"] = Header("接收者測試", 'utf-8') ## 接收者的別名smtp.sendmail(sender_qq_mail, receivers, msg.as_string()) smtp.quit()
執行上面代碼后,登錄接收郵件的郵件帳號,這里接收郵件的賬號為:yiibai.com@gmail.com
,登錄 http://gmail.com 應該會看到有接收到郵件如下 -
4.3.使用Python發送HTML格式的郵件
Python發送HTML格式的郵件與發送純文本消息的郵件不同之處就是將MIMEText中_subtype
設置為html
。代碼如下:
#! /usr/bin/env python#coding=utf-8from email.mime.text import MIMETextfrom email.header import Headerfrom smtplib import SMTP_SSL#qq郵箱smtp服務器host_server = 'smtp.qq.com'#sender_qq為發件人的qq號碼sender_qq = '7697****@qq.com'#pwd為qq郵箱的授權碼pwd = '***bmke********' ###發件人的郵箱sender_qq_mail = '7697****@qq.com'#收件人郵箱receiver = 'yiibai.com@gmail.com'#郵件的正文內容mail_content = "你好,<p>這是使用python登錄qq郵箱發送HTML格式郵件的測試:</p><p><a href='http://www.yiibai.com'>易百教程</a></p>"#郵件標題mail_title = 'Maxsu的郵件'#ssl登錄smtp = SMTP_SSL(host_server)#set_debuglevel()是用來調試的。參數值為1表示開啟調試模式,參數值為0關閉調試模式smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender_qq, pwd) msg = MIMEText(mail_content, "html", 'utf-8') msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_qq_mail msg["To"] = Header("接收者測試", 'utf-8') ## 接收者的別名smtp.sendmail(sender_qq_mail, receiver, msg.as_string()) smtp.quit()
執行上面代碼后,登錄接收郵件的郵件帳號,這里接收郵件的賬號為:yiibai.com@gmail.com
,登錄 http://gmail.com 應該會看到有接收到郵件如下 -
4.4.Python發送帶附件的郵件
要發送帶附件的郵件,首先要創建MIMEMultipart()
實例,然后構造附件,如果有多個附件,可依次構造,最后使用smtplib.smtp
發送。
實現代碼如下所示 -
#! /usr/bin/env python#coding=utf-8import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom smtplib import SMTP_SSLfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Header#qq郵箱smtp服務器host_server = 'smtp.qq.com'#sender_qq為發件人的qq號碼sender_qq = '7697****@qq.com'#pwd為qq郵箱的授權碼pwd = '*****mkenb****' ###發件人的郵箱sender_qq_mail = '7697****@qq.com'#收件人郵箱receiver = 'yiibai.com@gmail.com'#郵件的正文內容mail_content = "你好,<p>這是使用python登錄qq郵箱發送HTML格式郵件的測試:</p><p><a href='http://www.yiibai.com'>易百教程</a></p>"#郵件標題mail_title = 'Maxsu的郵件'#郵件正文內容msg = MIMEMultipart()#msg = MIMEText(mail_content, "plain", 'utf-8')msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_qq_mail msg["To"] = Header("接收者測試", 'utf-8') ## 接收者的別名#郵件正文內容msg.attach(MIMEText(mail_content, 'html', 'utf-8')) # 構造附件1,傳送當前目錄下的 test.txt 文件att1 = MIMEText(open('attach.txt', 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream'# 這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字att1["Content-Disposition"] = 'attachment; filename="attach.txt"'msg.attach(att1) # 構造附件2,傳送當前目錄下的 runoob.txt 文件att2 = MIMEText(open('yiibai.txt', 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream'att2["Content-Disposition"] = 'attachment; filename="yiibai.txt"'msg.attach(att2)#ssl登錄smtp = SMTP_SSL(host_server)#set_debuglevel()是用來調試的。參數值為1表示開啟調試模式,參數值為0關閉調試模式smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender_qq, pwd) smtp.sendmail(sender_qq_mail, receiver, msg.as_string()) smtp.quit()
執行上面代碼后,登錄接收郵件的郵件帳號,這里接收郵件的賬號為:yiibai.com@gmail.com
,登錄 http://gmail.com 應該會看到有接收到郵件如下 -
4.5.在 HTML 文本中添加圖片
郵件的HTML文本中一般郵件服務商添加外鏈是無效的,所以要發送帶圖片的郵件內容,可以參考下面的實例代碼實現:
#! /usr/bin/env python#coding=utf-8import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerfrom smtplib import SMTP_SSLfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText#qq郵箱smtp服務器host_server = 'smtp.qq.com'#sender_qq為發件人的qq號碼sender_qq = '7697****3@qq.com'#pwd為qq郵箱的授權碼pwd = 'h******mk*****' ##發件人的郵箱sender_qq_mail = '7697****3@qq.com'#收件人郵箱receiver = ['yiibai.com@gmail.com','h****u@qq.com']#郵件的正文內容mail_content = ""#郵件標題mail_title = 'Maxsu的郵件'#郵件正文內容#msg = MIMEMultipart()msg = MIMEMultipart('related') msg["Subject"] = Header(mail_title, 'utf-8') msg["From"] = sender_qq_mail msg["To"] = Header("接收者測試", 'utf-8') ## 接收者的別名msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative)#郵件正文內容mail_body = """ <p>你好,Python 郵件發送測試...</p> <p>這是使用python登錄qq郵箱發送HTML格式和圖片的測試郵件:</p> <p><a href='http://www.yiibai.com'>易百教程</a></p> <p>圖片演示:</p> <p></p> """#msg.attach(MIMEText(mail_body, 'html', 'utf-8'))msgText = (MIMEText(mail_body, 'html', 'utf-8')) msgAlternative.attach(msgText) # 指定圖片為當前目錄fp = open('my.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # 定義圖片 ID,在 HTML 文本中引用msgImage.add_header('Content-ID', '<send_image>') msg.attach(msgImage)#ssl登錄smtp = SMTP_SSL(host_server)#set_debuglevel()是用來調試的。參數值為1表示開啟調試模式,參數值為0關閉調試模式smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender_qq, pwd) smtp.sendmail(sender_qq_mail, receiver, msg.as_string()) smtp.quit()
執行上面代碼后,登錄接收郵件的郵件帳號,這里接收郵件的賬號為:yiibai.com@gmail.com
,登錄 http://gmail.com 應該會看到有接收到郵件如下 -電動叉車