Python用20行代碼實(shí)現(xiàn)完整郵件功能
Python實(shí)現(xiàn)完整郵件
先上效果:

一、郵箱端設(shè)置
首先,要對(duì)郵件進(jìn)行一下設(shè)置,在郵箱端獲取一個(gè)授權(quán)碼。
1、首先登錄網(wǎng)頁(yè)版126郵箱

2、打開(kāi) 設(shè)置—POP3/SMTP/IMAP配置界面

3、新增一個(gè)授權(quán)碼

二、python發(fā)送郵件
1、安裝郵件模塊
pip install py-emails
2、調(diào)用模塊
引入郵箱模塊,配置收件人、發(fā)件人、授權(quán)碼等信息
#引入smtplib模塊 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage #配置郵箱信息 sender = 'pacersby@126.com' #發(fā)件人的地址 password = 'XXXXXXXXXXXX' #此處是我們剛剛在郵箱中獲取的授權(quán)碼 receivers = ['wangsicong@126.com', '1029925144@qq.com'] #郵件接受方郵箱地址,可以配置多個(gè),實(shí)現(xiàn)群發(fā)
3、設(shè)置郵件內(nèi)容
#郵件內(nèi)容設(shè)置
message = MIMEText('你好呀,王思聰~~~','plain','utf-8')
#郵件標(biāo)題設(shè)置
message['Subject'] = '來(lái)自CSDN的問(wèn)候'
#發(fā)件人信息
message['From'] = sender
#收件人信息
message['To'] = receivers[0]
#通過(guò)授權(quán)碼,登錄郵箱,并發(fā)送郵件
try:
server = smtplib.SMTP('smtp.126.com') #配置126郵箱的smtp服務(wù)器地址
server.login(sender,password)
server.sendmail(sender, receivers, message.as_string())
print('發(fā)送成功')
server.quit()
except smtplib.SMTPException as e:
print('error',e)
4、添加附件
另外,我們發(fā)送郵件時(shí),經(jīng)常需要添加各式各樣的附件。python同樣可以實(shí)現(xiàn)。
如下,我們可以通過(guò)代碼添加圖片、pdf、zip等等格式的附件。
#添加圖片附件
imageFile = 'C:\\Users\\pacer\\Desktop\\img\\1.png'
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
#添加pdf附件
pdfFile = 'C:\\Users\\pacer\\Desktop\\img\\1.pdf'
pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
#添加壓縮文件附件
zipFile = 'C:\\Users\\pacer\\Desktop\\img\\1.zip'
zipApart = MIMEApplication(open(zipFile, 'rb').read())
zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)
三、python讀取郵件
通過(guò)我們?cè)O(shè)置的授權(quán)碼,登錄郵箱賬號(hào),獲取該賬號(hào)收到的郵件內(nèi)容。
首先安裝zmail模塊
pip install zmail
讀取郵件
server = zmail.server('pacersby@126.com','授權(quán)碼')
mail = server.get_latest()
zmail.show(mail)
獲取郵件效果如下:
------------------------- Subject 來(lái)自lex的python自動(dòng)發(fā)送郵件 Id 4 From pacersby@126.com To None Date 2021-07-15 10:18:39+08:00 Content_text ['來(lái)自lex的python自動(dòng)發(fā)送郵件'] Content_html [] Attachments 1.Name:C:\\Users\\lex\\Desktop\\img\\1.jpg Size:205133 2.Name:C:\\Users\\lex\\Desktop\\img\\1.pdf Size:434938 3.Name:C:\\Users\\lex\\Desktop\\img\\1.zip Size:1201666
以上就是Python用20行代碼實(shí)現(xiàn)完整郵件功能 的詳細(xì)內(nèi)容,更多關(guān)于Python實(shí)現(xiàn)完整郵件的資料請(qǐng)關(guān)注本站其它相關(guān)文章!希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信