本篇文章為大家展示了如何在Python中基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
SMTP(Simple Mail Transfer Protocol),即簡單郵件傳輸協(xié)議,它是一組由源地址到目的地址傳送郵件的規(guī)則,由它來控制信件的中轉(zhuǎn)方式。Python內(nèi)置對SMTP的支持,可以發(fā)送純文本郵件、HTML郵件以及帶附件的郵件。
Python對SMTP支持有smtplib
和email
兩個(gè)模塊,email
負(fù)責(zé)構(gòu)造郵件,smtplib
負(fù)責(zé)發(fā)送郵件。
Python創(chuàng)建SMTP語法如下:
import smtplib smtpObj = mstplib.SMTP(host,port)
創(chuàng)建具有SSL協(xié)議的SMTP:
import smtplib smtpObj = mstplib.SMTP_SSL(host,port)
使用SMTP對象發(fā)送郵件:
# from_addr:發(fā)送者郵箱 # to_addrs:接收者郵箱,list # msg:消息體 smtpObj.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
接下來的示例都是以網(wǎng)易郵箱作為郵箱服務(wù)器來寫的,網(wǎng)易163免費(fèi)郵箱相關(guān)服務(wù)器信息如下:
使用網(wǎng)易郵箱作為發(fā)送者郵箱時(shí)應(yīng)注意,郵箱密碼并非為郵箱的登錄密碼,而是客戶端授權(quán)密碼。
發(fā)送純文本郵件
首先,我們需要構(gòu)造一個(gè)消息體:
from email.header import Header from email.mime.text import MIMEText # 第一個(gè)參數(shù)為郵件正文,第二個(gè)參數(shù)為MINE的subtype,傳入‘plain',最終的MINE就是‘text/plain',最后參數(shù)為編碼 msg = MIMEText('hello email','palin','utf-8') def _format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr)) # 發(fā)送者昵稱 msg['From'] = _format_addr('發(fā)送者昵稱 <%s>'%from_addr) # 接收者昵稱 msg['To'] = _format_addr('接收者昵稱 <%s>'%to_addr) # 標(biāo)題 msg['Subject'] = Header('標(biāo)題','utf-8').encode()
此時(shí)就構(gòu)造了一個(gè)簡單的消息體。切記,如果未指定標(biāo)題以及昵稱,并且將其格式化編碼,有可能會(huì)被認(rèn)為是辣雞郵件而導(dǎo)致發(fā)送失?。。?!
以下就是發(fā)送純文本郵件示例的完整代碼:
import smtplib from email.header import Header from email.mime.text import MIMEText from email.utils import formataddr,parseaddr host = 'smtp.163.com' port = 25 from_addr = 'xxxx@163.com' from_addr_pwd = 'xxxxxx' to_addr = 'xxxx@qq.com' def _format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr)) msg = MIMEText('hello email','palin','utf-8') msg['From'] = _format_addr('發(fā)送者昵稱 <%s>'%from_addr) msg['To'] = _format_addr('接收者昵稱 <%s>'%to_addr) msg['Subject'] = Header('標(biāo)題','utf-8').encode() smtpObj = smtplib.SMTP(host,25) smtpObj.set_debuglevel(1) smtpObj.login(sender,password) smtpObj.sendmail(sender, [receivers], message.as_string()) smtoObj.quit()
值得注意的是,調(diào)用sendmail
方法時(shí),接收者郵箱為一個(gè)list類型,用于群發(fā)功能。
發(fā)送HTML郵件
如果有發(fā)送HTML郵件的需求,此時(shí)我們?nèi)孕柘葔蛑粋€(gè)MIMEText
對象,將html字符串傳遞進(jìn)來,如下:
htmlStr = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>Hello SMTP</h2> <p>點(diǎn)擊<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >鏈接</a></p> </body> </html>''' msg = MIMEText(htmlStr,'html','utf-8')
完整代碼如下:
import smtplib from email.mime.text import MIMEText from email.header import Header from email.utils import formataddr,parseaddr def _format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr)) server = 'smtp.163.com' from_addr = 'xxx@163.com' from_addr_pwd = 'xxxxxx' to_addr = 'xxx1@qq.com' htmlStr = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>Hello SMTP</h2> <p>點(diǎn)擊<a href="https://www.baidu.com" rel="external nofollow" rel="external nofollow" >鏈接</a></p> </body> </html>''' msg = MIMEText(htmlStr,'html','utf-8') msg['From'] = _format_addr("發(fā)送者 <%s>"%from_addr) msg['To'] = _format_addr("接收者 <%s>"%to_addr) msg['Subject'] = Header('一個(gè)簡單的標(biāo)題','utf-8').encode() smtpObj = smtplib.SMTP(server,25) smtpObj.set_debuglevel(1) smtpObj.login(from_addr,from_addr_pwd) smtpObj.sendmail(from_addr,[to_addr],msg.as_string()) smtpObj.quit()
發(fā)送附件郵件
如果我們有發(fā)送附件的需求時(shí),我們該如何改造消息體呢?我們此時(shí)可以用MIMEMultipart
構(gòu)造郵件的本身,傳遞一個(gè)MIMEText
對象來寫入郵件的正文,再用MIMEBase
對象存儲附件的信息即可,代碼如下:
msg = MIMEMultipart() msg.attach(MIMEText('發(fā)送一個(gè)附件...','plain','utf-8')) path = os.path.join(os.getcwd(),'1.png') with open(path,'rb') as f: # 設(shè)置附件的MIME mime = MIMEBase('image','png',filename='1.png') # 加上必要的頭信息 mime.add_header('Content-Disposition','attachment',filename='1.png') mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') # 讀取文件內(nèi)容 mime.set_payload(f.read()) # 使用base64編碼 encode_base64(mime) msg.attach(mime)
完整代碼如下:
import smtplib,os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart,MIMEBase from email.header import Header from email.encoders import encode_base64 from email.utils import formataddr,parseaddr msg = MIMEMultipart() msg.attach(MIMEText('發(fā)送一個(gè)附件...','plain','utf-8')) def _format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr)) server = 'smtp.163.com' from_addr = 'xxx@163.com' from_addr_pwd = 'xxxxxx' to_addr = 'xxx1@qq.com' path = os.path.join(os.getcwd(),'1.png') with open(path,'rb') as f: mime = MIMEBase('image','png',filename='1.png') mime.add_header('Content-Disposition','attachment',filename='1.png') mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') mime.set_payload(f.read()) encode_base64(mime) msg.attach(mime) msg['From'] = _format_addr("發(fā)送者 <%s>"%from_addr) msg['To'] = _format_addr("接收者 <%s>"%to_addr) msg['Subject'] = Header('一個(gè)簡單的附件郵件','utf-8').encode() smtpObj = smtplib.SMTP(server,25) smtpObj.set_debuglevel(1) smtpObj.login(from_addr,from_addr_pwd) smtpObj.sendmail(from_addr,[to_addr],msg.as_string()) smtpObj.quit()
發(fā)送圖片郵件
如果我們需要在一段文本中插入圖片作為郵件正文,那么我們該如何實(shí)現(xiàn)呢?有人會(huì)想用HTML,在里面嵌一個(gè)img標(biāo)簽就可以了,但是這樣有一個(gè)問題,因?yàn)閕mg標(biāo)簽是引用一個(gè)圖片路徑的,我們總不能將圖片文件也發(fā)送過去吧。那么久沒有辦法了嗎,當(dāng)然有,我們可以結(jié)合HTML與附件郵件發(fā)送方式來發(fā)送圖片郵件,首先我們將圖片以附件的形式添加進(jìn)來,再以HTML中img標(biāo)簽引用src='cid:0'
,就可以將圖片引用進(jìn)來了,如下:
msg = MIMEMultipart() path = os.path.join(os.getcwd(),'1.png') with open(path,'rb') as f: mime = MIMEBase('image','png',filename='1.png') mime.add_header('Content-Disposition','attachment',filename='1.png') mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') mime.set_payload(f.read()) encode_base64(mime) msg.attach(mime) htmlStr = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>圖片標(biāo)題</h2> <p>插入一個(gè)圖片<img src="cid:0"/></p> </body> </html>''' msg.attach(MIMEText(htmlStr,'html','utf-8'))
完整代碼如下:
import smtplib,os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart,MIMEBase from email.header import Header from email.encoders import encode_base64 from email.utils import parseaddr,formataddr server = 'smtp.163.com' from_addr = 'xxx@163.com' from_addr_pwd = 'xxxxxx' to_addr = 'xxx1@qq.com' def _format_addr(s): name,addr = parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr,unicode) else addr)) msg = MIMEMultipart() path = os.path.join(os.getcwd(),'1.png') with open(path,'rb') as f: # 設(shè)置附件的MIME mime = MIMEBase('image','png',filename='1.png') # 加上必要的頭信息 mime.add_header('Content-Disposition','attachment',filename='1.png') mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') # 讀取文件內(nèi)容 mime.set_payload(f.read()) # 使用base64編碼 encode_base64(mime) msg.attach(mime) htmlStr = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>圖片標(biāo)題</h2> <p>插入一個(gè)圖片<img src="cid:0"/></p> </body> </html>''' msg.attach(MIMEText(htmlStr,'html','utf-8')) msg['From'] = _format_addr('發(fā)送者 <%s>'%from_addr) msg['To'] = _format_addr('接收者 <%s>'%to_addr) msg['Subject'] = Header('發(fā)送圖片郵件','utf-8').encode() smtpObj = smtplib.SMTP(server,25) smtpObj.set_debuglevel(1) smtpObj.login(from_addr,from_addr_pwd) smtpObj.sendmail(from_addr,[to_addr],msg.as_string()) smtpObj.quit()
上述內(nèi)容就是如何在Python中基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章名稱:如何在Python中基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能-創(chuàng)新互聯(lián)
鏈接URL:http://chinadenli.net/article20/dgphjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、虛擬主機(jī)、響應(yīng)式網(wǎng)站、服務(wù)器托管、靜態(tài)網(wǎng)站、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容