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

錯誤總結(jié)
我遇到的錯誤如下:
D:\Software\Python2\python.exe E:/Code/Python/MyTestSet/mail/withappedix.py Traceback (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
我的解決辦法是
receiver parameter was list type. either it should be list converted to string using join method or if it is a single recipient, then pass it as a string only
是的,就是receivers = ','.join(['10XXXXXXXX@qq.com'])。這樣就搞定了。
也許,你遇到的錯誤不是我這個,那么也不用擔心,我這里有一份比較齊全的錯誤碼對照表。你可以對照著你的錯誤碼來查找具體的錯誤原因。這樣有的放矢,效率會更高一點的。
在編碼的過程中,我也是遇到了很多意想不到的錯誤。而這些錯誤的錯誤碼對我們來說是很有用的。這對我們測試代碼以及找到其中出錯的原因和有幫助。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pandas讀取文件夾下所有excel文件的實現(xiàn)
最近需要做一個需求,要求匯總一個文件夾所有的excel文件,所以本文就來介紹一下pandas讀取文件夾下所有excel文件的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-09-09
tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解
本文主要介紹了tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
django haystack實現(xiàn)全文檢索的示例代碼
這篇文章主要介紹了django haystack實現(xiàn)全文檢索的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
查看TensorFlow checkpoint文件中的變量名和對應(yīng)值方法
今天小編就為大家分享一篇查看TensorFlow checkpoint文件中的變量名和對應(yīng)值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
在Python中等距取出一個數(shù)組其中n個數(shù)的實現(xiàn)方式
今天小編就為大家分享一篇在Python中等距取出一個數(shù)組其中n個數(shù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

