Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例
這兩天對Python的郵件模塊比較感興趣,于是就查了查資料。同時在實(shí)際的編碼過程中也遇到了各種各樣的問題。下面我就來分享一下我與smtplib的故事。
前提條件
我的上一篇博文里面講解了,發(fā)送郵件必須的條件。這里同樣是適用的。大致就是要開啟郵箱的SMPT/POP服務(wù)等等。
核心知識點(diǎn)
因?yàn)榻裉熘饕v解的是如何發(fā)送帶有附件的郵件,那么核心肯定是附件了。怎么才能發(fā)附件呢?
其實(shí)我們換個思路,就不難理解了。因?yàn)槲覀儼l(fā)送郵件,經(jīng)過了應(yīng)用層–>> 傳輸層–>> 網(wǎng)絡(luò)層–>>數(shù)據(jù)鏈路層–>>物理層。這一系列的步驟,全都變成了比特流了。所以無論是純文本,圖片,亦或是其他類型的文件。在比特流的面前,都是平等的。所以我們發(fā)送附件,也是按照發(fā)送純文本的模式來做就行,只不過加上一些特殊的標(biāo)記即可。
\# 首先是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進(jìn)行包裝一下,然后設(shè)置一下內(nèi)容。最后添加到郵件內(nèi)容。就是這幾步,就搞定了。
完整的代碼
# coding:utf-8
# __author__ = 'Mark sinoberg'
# __date__ = '2016/5/26'
# __Desc__ = 實(shí)現(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
驗(yàn)證結(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'])。這樣就搞定了。
也許,你遇到的錯誤不是我這個,那么也不用擔(dān)心,我這里有一份比較齊全的錯誤碼對照表。你可以對照著你的錯誤碼來查找具體的錯誤原因。這樣有的放矢,效率會更高一點(diǎn)的。
在編碼的過程中,我也是遇到了很多意想不到的錯誤。而這些錯誤的錯誤碼對我們來說是很有用的。這對我們測試代碼以及找到其中出錯的原因和有幫助。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python使用QQ郵箱發(fā)送郵件報(bào)錯smtplib.SMTPAuthenticationError
- python smtplib發(fā)送帶附件郵件小程序
- python3模塊smtplib實(shí)現(xiàn)發(fā)送郵件功能
- python3使用smtplib實(shí)現(xiàn)發(fā)送郵件功能
- python smtplib模塊自動收發(fā)郵件功能(一)
- python利用smtplib實(shí)現(xiàn)QQ郵箱發(fā)送郵件
- python使用電子郵件模塊smtplib的方法
- Python基于smtplib協(xié)議實(shí)現(xiàn)發(fā)送郵件
相關(guān)文章
python tkinter中的錨點(diǎn)(anchor)問題及處理
這篇文章主要介紹了python tkinter中的錨點(diǎn)(anchor)問題及處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
Python文件操作JSON CSV TSV Excel和Pickle文件序列化
這篇文章主要為大家介紹了Python文件操作之JSON、CSV、TSV、Excel和Pickle文件序列化示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
Python+Redis實(shí)現(xiàn)布隆過濾器
布隆過濾器(Bloom Filter)是1970年由布隆提出的。它實(shí)際上是一個很長的二進(jìn)制向量和一系列隨機(jī)映射函數(shù)。這篇文章主要介紹了Python+Redis實(shí)現(xiàn)布隆過濾器,需要的朋友可以參考下2019-12-12
python pytorch模型轉(zhuǎn)onnx模型的全過程(多輸入+動態(tài)維度)
這篇文章主要介紹了python pytorch模型轉(zhuǎn)onnx模型的全過程(多輸入+動態(tài)維度),本文給大家記錄記錄了pt文件轉(zhuǎn)onnx全過程,簡單的修改即可應(yīng)用,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-03-03
Python?Pandas多種添加行列數(shù)據(jù)方法總結(jié)
在進(jìn)行數(shù)據(jù)分析時經(jīng)常需要按照一定條件創(chuàng)建新的數(shù)據(jù)列,然后進(jìn)行進(jìn)一步分析,下面這篇文章主要給大家介紹了關(guān)于Python?Pandas多種添加行列數(shù)據(jù)方法的相關(guān)資料,需要的朋友可以參考下2022-07-07
Python基于tkinter模塊實(shí)現(xiàn)的改名小工具示例
這篇文章主要介紹了Python基于tkinter模塊實(shí)現(xiàn)的改名小工具,結(jié)合實(shí)例形式分析了tkinter模塊操作文件后綴名的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-07-07

