簡(jiǎn)單郵件傳輸協(xié)議(SMTP)是一種協(xié)議,用于在郵件服務(wù)器之間發(fā)送電子郵件和路由電子郵件。
Python提供smtplib模塊,該模塊定義了一個(gè)SMTP客戶端會(huì)話對(duì)象,可用于使用SMTP或ESMTP偵聽器守護(hù)程序向任何互聯(lián)網(wǎng)機(jī)器發(fā)送郵件。
這是一個(gè)簡(jiǎn)單的語法,用來創(chuàng)建一個(gè)SMTP對(duì)象,稍后將演示如何用它來發(fā)送電子郵件 -
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
這里是上面語法的參數(shù)細(xì)節(jié) -
yiibai.com的域名。這是一個(gè)可選參數(shù)。25。localhost選項(xiàng)。SMTP對(duì)象有一個(gè)sendmail的實(shí)例方法,該方法通常用于執(zhí)行郵件發(fā)送的工作。它需要三個(gè)參數(shù) -
示例
以下是使用Python腳本發(fā)送一封電子郵件的簡(jiǎn)單方法 -
#!/usr/bin/python3
import 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"
在這里,已經(jīng)發(fā)送了一封基本的電子郵件,使用三重引號(hào),請(qǐng)注意正確格式化標(biāo)題。一封電子郵件需要一個(gè)From,To和一個(gè)Subject標(biāo)題,與電子郵件的正文與空白行分開。
要發(fā)送郵件,使用smtpObj連接到本地機(jī)器上的SMTP服務(wù)器。 然后使用sendmail方法以及消息,從地址和目標(biāo)地址作為參數(shù)(即使來自和地址在電子郵件本身內(nèi),這些并不總是用于路由郵件)。
如果沒有在本地計(jì)算機(jī)上運(yùn)行SMTP服務(wù)器,則可以使用smtplib客戶端與遠(yuǎn)程SMTP服務(wù)器進(jìn)行通信。除非您使用網(wǎng)絡(luò)郵件服務(wù)(如gmail或Yahoo! Mail),否則您的電子郵件提供商必須向您提供可以提供的郵件服務(wù)器詳細(xì)信息。以騰訊QQ郵箱為例,具體如下:
mail = smtplib.SMTP('smtp.qq.com', 587) # 端口465或587
當(dāng)使用Python發(fā)送郵件信息時(shí),所有內(nèi)容都被視為簡(jiǎn)單文本。 即使在短信中包含HTML標(biāo)簽,它也將顯示為簡(jiǎn)單的文本,HTML標(biāo)簽將不會(huì)根據(jù)HTML語法進(jìn)行格式化。 但是,Python提供了將HTML消息作為HTML消息發(fā)送的選項(xiàng)。
發(fā)送電子郵件時(shí),可以指定一個(gè)Mime版本,內(nèi)容類型和發(fā)送HTML電子郵件的字符集。
以下是將HTML內(nèi)容作為電子郵件發(fā)送的示例 -
#!/usr/bin/python3
import 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"
要發(fā)送具有混合內(nèi)容的電子郵件,需要將Content-type標(biāo)題設(shè)置為multipart / mixed。 然后,可以在邊界內(nèi)指定文本和附件部分。
一個(gè)邊界以兩個(gè)連字符開始,后跟一個(gè)唯一的編號(hào),不能出現(xiàn)在電子郵件的消息部分。 表示電子郵件最終部分的最后一個(gè)邊界也必須以兩個(gè)連字符結(jié)尾。
所附的文件應(yīng)該用包(“m”)功能編碼,以便在傳輸之前具有基本的64編碼。
首先我們要知道用python代理登錄qq郵箱發(fā)郵件,是需要更改自己qq郵箱設(shè)置的。在這里大家需要做兩件事情:郵箱開啟SMTP功能 、獲得授權(quán)碼。之后我們來看看如何更改模板代碼,實(shí)現(xiàn)使用Python登錄QQ郵箱發(fā)送QQ郵件。
注意:也可以使用其他服務(wù)商的 SMTP 訪問(QQ、網(wǎng)易、Gmail等)。
使用QQ郵件發(fā)送郵件之前如何設(shè)置授權(quán)碼,參考:
http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
4.1.發(fā)送一純文本郵件到指定郵件
#! /usr/bin/env python
#coding=utf-8
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
#qq郵箱smtp服務(wù)器
host_server = 'smtp.qq.com'
#sender_qq為發(fā)件人的qq號(hào)碼
sender_qq = '769728683@qq.com'
#pwd為qq郵箱的授權(quán)碼
pwd = '****kenbb***' ## xh**********bdc
#發(fā)件人的郵箱
sender_qq_mail = '769728683@qq.com'
#收件人郵箱
receiver = 'yiibai.com@gmail.com'
#郵件的正文內(nèi)容
mail_content = '你好,這是使用python登錄qq郵箱發(fā)郵件的測(cè)試'
#郵件標(biāo)題
mail_title = 'Maxsu的郵件'
#ssl登錄
smtp = SMTP_SSL(host_server)
#set_debuglevel()是用來調(diào)試的。參數(shù)值為1表示開啟調(diào)試模式,參數(shù)值為0關(guān)閉調(diào)試模式
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()
執(zhí)行上面代碼后,登錄接收郵件的郵件帳號(hào),這里接收郵件的賬號(hào)為:yiibai.com@gmail.com,登錄 http://gmail.com 應(yīng)該會(huì)看到有接收到郵件如下 -

注意:有時(shí)可能被認(rèn)為是垃圾郵件,如果沒有找到可從“垃圾郵件”查找一下。
4.2.給多個(gè)人發(fā)送郵件
#! /usr/bin/env python
#coding=utf-8
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
#qq郵箱smtp服務(wù)器
host_server = 'smtp.qq.com'
#sender_qq為發(fā)件人的qq號(hào)碼
sender_qq = '769728683@qq.com'
#pwd為qq郵箱的授權(quán)碼
pwd = 'h**********bdc' ## h**********bdc
#發(fā)件人的郵箱
sender_qq_mail = '769728683@qq.com'
#收件人郵箱
receivers = ['yiibai.com@gmail.com','****su@gmail.com']
#郵件的正文內(nèi)容
mail_content = '你好,這是使用python登錄qq郵箱發(fā)郵件的測(cè)試'
#郵件標(biāo)題
mail_title = 'Maxsu的郵件'
#ssl登錄
smtp = SMTP_SSL(host_server)
#set_debuglevel()是用來調(diào)試的。參數(shù)值為1表示開啟調(diào)試模式,參數(shù)值為0關(guān)閉調(diào)試模式
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("接收者測(cè)試", 'utf-8') ## 接收者的別名
smtp.sendmail(sender_qq_mail, receivers, msg.as_string())
smtp.quit()
執(zhí)行上面代碼后,登錄接收郵件的郵件帳號(hào),這里接收郵件的賬號(hào)為:yiibai.com@gmail.com,登錄 http://gmail.com 應(yīng)該會(huì)看到有接收到郵件如下 -

4.3.使用Python發(fā)送HTML格式的郵件
Python發(fā)送HTML格式的郵件與發(fā)送純文本消息的郵件不同之處就是將MIMEText中_subtype設(shè)置為html。代碼如下:
#! /usr/bin/env python
#coding=utf-8
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
#qq郵箱smtp服務(wù)器
host_server = 'smtp.qq.com'
#sender_qq為發(fā)件人的qq號(hào)碼
sender_qq = '769728683@qq.com'
#pwd為qq郵箱的授權(quán)碼
pwd = '***bmke********' ##
#發(fā)件人的郵箱
sender_qq_mail = '769728683@qq.com'
#收件人郵箱
receiver = 'yiibai.com@gmail.com'
#郵件的正文內(nèi)容
mail_content = "你好,<p>這是使用python登錄qq郵箱發(fā)送HTML格式郵件的測(cè)試:</p><p><a href='http://www.yiibai.com'>易百教程</a></p>"
#郵件標(biāo)題
mail_title = 'Maxsu的郵件'
#ssl登錄
smtp = SMTP_SSL(host_server)
#set_debuglevel()是用來調(diào)試的。參數(shù)值為1表示開啟調(diào)試模式,參數(shù)值為0關(guān)閉調(diào)試模式
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("接收者測(cè)試", 'utf-8') ## 接收者的別名
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
執(zhí)行上面代碼后,登錄接收郵件的郵件帳號(hào),這里接收郵件的賬號(hào)為:yiibai.com@gmail.com,登錄 http://gmail.com 應(yīng)該會(huì)看到有接收到郵件如下 -

4.4.Python發(fā)送帶附件的郵件
要發(fā)送帶附件的郵件,首先要?jiǎng)?chuàng)建MIMEMultipart()實(shí)例,然后構(gòu)造附件,如果有多個(gè)附件,可依次構(gòu)造,最后使用smtplib.smtp發(fā)送。
實(shí)現(xiàn)代碼如下所示 -
#! /usr/bin/env python
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
#qq郵箱smtp服務(wù)器
host_server = 'smtp.qq.com'
#sender_qq為發(fā)件人的qq號(hào)碼
sender_qq = '769728683@qq.com'
#pwd為qq郵箱的授權(quán)碼
pwd = '*****mkenb****' ##
#發(fā)件人的郵箱
sender_qq_mail = '769728683@qq.com'
#收件人郵箱
receiver = 'yiibai.com@gmail.com'
#郵件的正文內(nèi)容
mail_content = "你好,<p>這是使用python登錄qq郵箱發(fā)送HTML格式郵件的測(cè)試:</p><p><a href='http://www.yiibai.com'>易百教程</a></p>"
#郵件標(biāo)題
mail_title = 'Maxsu的郵件'
#郵件正文內(nèi)容
msg = MIMEMultipart()
#msg = MIMEText(mail_content, "plain", 'utf-8')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq_mail
msg["To"] = Header("接收者測(cè)試", 'utf-8') ## 接收者的別名
#郵件正文內(nèi)容
msg.attach(MIMEText(mail_content, 'html', 'utf-8'))
# 構(gòu)造附件1,傳送當(dāng)前目錄下的 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)
# 構(gòu)造附件2,傳送當(dāng)前目錄下的 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()是用來調(diào)試的。參數(shù)值為1表示開啟調(diào)試模式,參數(shù)值為0關(guān)閉調(diào)試模式
smtp.set_debuglevel(1)
smtp.ehlo(host_server)
smtp.login(sender_qq, pwd)
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
執(zhí)行上面代碼后,登錄接收郵件的郵件帳號(hào),這里接收郵件的賬號(hào)為:yiibai.com@gmail.com,登錄 http://gmail.com 應(yīng)該會(huì)看到有接收到郵件如下 -

4.5.在 HTML 文本中添加圖片
郵件的HTML文本中一般郵件服務(wù)商添加外鏈?zhǔn)菬o效的,所以要發(fā)送帶圖片的郵件內(nèi)容,可以參考下面的實(shí)例代碼實(shí)現(xiàn):
#! /usr/bin/env python
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#qq郵箱smtp服務(wù)器
host_server = 'smtp.qq.com'
#sender_qq為發(fā)件人的qq號(hào)碼
sender_qq = '769728683@qq.com'
#pwd為qq郵箱的授權(quán)碼
pwd = 'h******mk*****' #
#發(fā)件人的郵箱
sender_qq_mail = '769728683@qq.com'
#收件人郵箱
receiver = ['yiibai.com@gmail.com','h****u@qq.com']
#郵件的正文內(nèi)容
mail_content = ""
#郵件標(biāo)題
mail_title = 'Maxsu的郵件'
#郵件正文內(nèi)容
#msg = MIMEMultipart()
msg = MIMEMultipart('related')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq_mail
msg["To"] = Header("接收者測(cè)試", 'utf-8') ## 接收者的別名
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
#郵件正文內(nèi)容
mail_body = """
<p>你好,Python 郵件發(fā)送測(cè)試...</p>
<p>這是使用python登錄qq郵箱發(fā)送HTML格式和圖片的測(cè)試郵件:</p>
<p><a href='http://www.yiibai.com'>易百教程</a></p>
<p>圖片演示:</p>
<p><img src="cid:send_image"></p>
"""
#msg.attach(MIMEText(mail_body, 'html', 'utf-8'))
msgText = (MIMEText(mail_body, 'html', 'utf-8'))
msgAlternative.attach(msgText)
# 指定圖片為當(dāng)前目錄
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()是用來調(diào)試的。參數(shù)值為1表示開啟調(diào)試模式,參數(shù)值為0關(guān)閉調(diào)試模式
smtp.set_debuglevel(1)
smtp.ehlo(host_server)
smtp.login(sender_qq, pwd)
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
執(zhí)行上面代碼后,登錄接收郵件的郵件帳號(hào),這里接收郵件的賬號(hào)為:yiibai.com@gmail.com,登錄 http://gmail.com 應(yīng)該會(huì)看到有接收到郵件如下 -
