這兩天對(duì)Python的郵件模塊比較感興趣,于是就查了查資料。同時(shí)在實(shí)際的編碼過(guò)程中也遇到了各種各樣的問(wèn)題。下面我就來(lái)分享一下我與python/199468.html">smtplib的故事。
前提條件
我的上一篇博文里面講解了,發(fā)送郵件必須的條件。這里同樣是適用的。大致就是要開(kāi)啟郵箱的SMPT/POP服務(wù)等等。
核心知識(shí)點(diǎn)
因?yàn)榻裉熘饕v解的是如何發(fā)送帶有附件的郵件,那么核心肯定是附件了。怎么才能發(fā)附件呢?
其實(shí)我們換個(gè)思路,就不難理解了。因?yàn)槲覀儼l(fā)送郵件,經(jīng)過(guò)了應(yīng)用層–>> 傳輸層–>> 網(wǎng)絡(luò)層–>>數(shù)據(jù)鏈路層–>>物理層。這一系列的步驟,全都變成了比特流了。所以無(wú)論是純文本,圖片,亦或是其他類(lèi)型的文件。在比特流的面前,都是平等的。所以我們發(fā)送附件,也是按照發(fā)送純文本的模式來(lái)做就行,只不過(guò)加上一些特殊的標(biāo)記即可。
/# 首先是xlsx類(lèi)型的附件xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read())xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx')msg.attach(xlsxpart)/# jpg類(lèi)型的附件jpgpart = MIMEApplication(open('beauty.jpg', 'rb').read())jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg')msg.attach(jpgpart)/# mp3類(lèi)型的附件mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')msg.attach(mp3part)經(jīng)過(guò)這三小段的代碼,想必你已經(jīng)很清楚了吧。無(wú)非就是使用MIMEApplication進(jìn)行包裝一下,然后設(shè)置一下內(nèi)容。最后添加到郵件內(nèi)容。就是這幾步,就搞定了。
完整的代碼
# coding:utf-8# __author__ = 'Mark sinoberg'# __date__ = '2016/5/26'# __Desc__ = 實(shí)現(xiàn)發(fā)送帶有各種附件類(lèi)型的郵件import urllib, urllib2import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplicationusername = '156408XXXXX@163.com'password = 'XXXXXXXX'sender = usernamereceivers = ','.join(['10643XXXX2@qq.com'])# 如名字所示: Multipart就是多個(gè)部分msg = MIMEMultipart()msg['Subject'] = 'Python mail Test'msg['From'] = sendermsg['To'] = receivers# 下面是文字部分,也就是純文本puretext = MIMEText('我是純文本部分,')msg.attach(puretext)# 下面是附件部分 ,這里分為了好幾個(gè)類(lèi)型# 首先是xlsx類(lèi)型的附件xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read())xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx')msg.attach(xlsxpart)# jpg類(lèi)型的附件jpgpart = MIMEApplication(open('beauty.jpg', 'rb').read())jpgpart.add_header('Content-Disposition', 'attachment', filename='beauty.jpg')msg.attach(jpgpart)# mp3類(lèi)型的附件mp3part = MIMEApplication(open('kenny.mp3', 'rb').read())mp3part.add_header('Content-Disposition', 'attachment', filename='benny.mp3')msg.attach(mp3part)## 下面開(kāi)始真正的發(fā)送郵件了try: client = smtplib.SMTP() client.connect('smtp.163.com') client.login(username, password) client.sendmail(sender, receivers, msg.as_string()) client.quit() print '帶有各種附件的郵件發(fā)送成功!'except smtplib.SMTPRecipientsRefused: print 'Recipient refused'except smtplib.SMTPAuthenticationError: print 'Auth error'except smtplib.SMTPSenderRefused: print 'Sender refused'except smtplib.SMTPException,e: print e.message
驗(yàn)證結(jié)果
沒(méi)有什么比來(lái)張圖片更有說(shuō)服力的了。如圖

錯(cuò)誤總結(jié)
我遇到的錯(cuò)誤如下:
D:/Software/Python2/python.exe E:/Code/Python/MyTestSet/mail/withappedix.pyTraceback (most recent call last): File "E:/Code/Python/MyTestSet/mail/withappedix.py", line 51, in <module> client.sendmail(sender, receivers, msg.as_string()) File "D:/Software/Python2/lib/email/message.py", line 137, in as_string g.flatten(self, unixfrom=unixfrom) File "D:/Software/Python2/lib/email/generator.py", line 83, in flatten self._write(msg) File "D:/Software/Python2/lib/email/generator.py", line 115, in _write self._write_headers(msg) File "D:/Software/Python2/lib/email/generator.py", line 164, in _write_headers v, maxlinelen=self._maxheaderlen, header_name=h).encode() File "D:/Software/Python2/lib/email/header.py", line 410, in encode value = self._encode_chunks(newchunks, maxlinelen) File "D:/Software/Python2/lib/email/header.py", line 370, in _encode_chunks _max_append(chunks, s, maxlinelen, extra) File "D:/Software/Python2/lib/email/quoprimime.py", line 97, in _max_append L.append(s.lstrip())AttributeError: 'list' object has no attribute 'lstrip'Process finished with exit code 1
我的解決辦法是
是的,就是receivers = ','.join(['10XXXXXXXX@qq.com'])。這樣就搞定了。
也許,你遇到的錯(cuò)誤不是我這個(gè),那么也不用擔(dān)心,我這里有一份比較齊全的錯(cuò)誤碼對(duì)照表。你可以對(duì)照著你的錯(cuò)誤碼來(lái)查找具體的錯(cuò)誤原因。這樣有的放矢,效率會(huì)更高一點(diǎn)的。
在編碼的過(guò)程中,我也是遇到了很多意想不到的錯(cuò)誤。而這些錯(cuò)誤的錯(cuò)誤碼對(duì)我們來(lái)說(shuō)是很有用的。這對(duì)我們測(cè)試代碼以及找到其中出錯(cuò)的原因和有幫助。
企業(yè)退信的錯(cuò)誤碼對(duì)照表
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選