您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何在Python中基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
SMTP(Simple Mail Transfer Protocol),即簡(jiǎn)單郵件傳輸協(xié)議,它是一組由源地址到目的地址傳送郵件的規(guī)則,由它來(lái)控制信件的中轉(zhuǎn)方式。Python內(nèi)置對(duì)SMTP的支持,可以發(fā)送純文本郵件、HTML郵件以及帶附件的郵件。
Python對(duì)SMTP支持有smtplib
和email
兩個(gè)模塊,email
負(fù)責(zé)構(gòu)造郵件,smtplib
負(fù)責(zé)發(fā)送郵件。
Python創(chuàng)建SMTP語(yǔ)法如下:
import smtplib smtpObj = mstplib.SMTP(host,port)
創(chuàng)建具有SSL協(xié)議的SMTP:
import smtplib smtpObj = mstplib.SMTP_SSL(host,port)
使用SMTP對(duì)象發(fā)送郵件:
# from_addr:發(fā)送者郵箱 # to_addrs:接收者郵箱,list # msg:消息體 smtpObj.sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
接下來(lái)的示例都是以網(wǎng)易郵箱作為郵箱服務(wù)器來(lái)寫(xiě)的,網(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è)簡(jiǎn)單的消息體。切記,如果未指定標(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
對(duì)象,將html字符串傳遞進(jìn)來(lái),如下:
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è)簡(jiǎn)單的標(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í),我們?cè)撊绾胃脑煜Ⅲw呢?我們此時(shí)可以用MIMEMultipart
構(gòu)造郵件的本身,傳遞一個(gè)MIMEText
對(duì)象來(lái)寫(xiě)入郵件的正文,再用MIMEBase
對(duì)象存儲(chǔ)附件的信息即可,代碼如下:
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è)簡(jiǎn)單的附件郵件','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ā)送圖片郵件
如果我們需要在一段文本中插入圖片作為郵件正文,那么我們?cè)撊绾螌?shí)現(xiàn)呢?有人會(huì)想用HTML,在里面嵌一個(gè)img標(biāo)簽就可以了,但是這樣有一個(gè)問(wèn)題,因?yàn)閕mg標(biāo)簽是引用一個(gè)圖片路徑的,我們總不能將圖片文件也發(fā)送過(guò)去吧。那么久沒(méi)有辦法了嗎,當(dāng)然有,我們可以結(jié)合HTML與附件郵件發(fā)送方式來(lái)發(fā)送圖片郵件,首先我們將圖片以附件的形式添加進(jìn)來(lái),再以HTML中img標(biāo)簽引用src='cid:0'
,就可以將圖片引用進(jìn)來(lái)了,如下:
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é)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。