本篇文章為大家展示了如何在Python中基于SMTP協(xié)議實(shí)現(xiàn)發(fā)送郵件功能,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)執(zhí)著的堅(jiān)持網(wǎng)站建設(shè),小程序制作;我們不會(huì)轉(zhuǎn)行,已經(jīng)持續(xù)穩(wěn)定運(yùn)營(yíng)十多年。專業(yè)的技術(shù),豐富的成功經(jīng)驗(yàn)和創(chuàng)作思維,提供一站式互聯(lián)網(wǎng)解決方案,以客戶的口碑塑造品牌,攜手廣大客戶,共同發(fā)展進(jìn)步。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)寫的,網(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 = '''Title Hello SMTP
點(diǎn)擊鏈接
''' 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 = '''Title Hello SMTP
點(diǎn)擊鏈接
''' 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)寫入郵件的正文,再用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è)問題,因?yàn)閕mg標(biāo)簽是引用一個(gè)圖片路徑的,我們總不能將圖片文件也發(fā)送過(guò)去吧。那么久沒有辦法了嗎,當(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 = '''Title 圖片標(biāo)題
插入一個(gè)圖片
''' 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 = '''Title 圖片標(biāo)題
插入一個(gè)圖片
''' 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)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。