Python用20行代碼實現(xiàn)完整郵件功能
Python實現(xiàn)完整郵件
先上效果:
一、郵箱端設置
首先,要對郵件進行一下設置,在郵箱端獲取一個授權碼。
1、首先登錄網(wǎng)頁版126郵箱
2、打開 設置—POP3/SMTP/IMAP配置界面
3、新增一個授權碼
二、python發(fā)送郵件
1、安裝郵件模塊
pip install py-emails
2、調(diào)用模塊
引入郵箱模塊,配置收件人、發(fā)件人、授權碼等信息
#引入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' #此處是我們剛剛在郵箱中獲取的授權碼 receivers = ['wangsicong@126.com', '1029925144@qq.com'] #郵件接受方郵箱地址,可以配置多個,實現(xiàn)群發(fā)
3、設置郵件內(nèi)容
#郵件內(nèi)容設置 message = MIMEText('你好呀,王思聰~~~','plain','utf-8') #郵件標題設置 message['Subject'] = '來自CSDN的問候' #發(fā)件人信息 message['From'] = sender #收件人信息 message['To'] = receivers[0] #通過授權碼,登錄郵箱,并發(fā)送郵件 try: server = smtplib.SMTP('smtp.126.com') #配置126郵箱的smtp服務器地址 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ā)送郵件時,經(jīng)常需要添加各式各樣的附件。python同樣可以實現(xiàn)。
如下,我們可以通過代碼添加圖片、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讀取郵件
通過我們設置的授權碼,登錄郵箱賬號,獲取該賬號收到的郵件內(nèi)容。
首先安裝zmail模塊
pip install zmail
讀取郵件
server = zmail.server('pacersby@126.com','授權碼') mail = server.get_latest() zmail.show(mail)
獲取郵件效果如下:
------------------------- Subject 來自lex的python自動發(fā)送郵件 Id 4 From pacersby@126.com To None Date 2021-07-15 10:18:39+08:00 Content_text ['來自lex的python自動發(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行代碼實現(xiàn)完整郵件功能 的詳細內(nèi)容,更多關于Python實現(xiàn)完整郵件的資料請關注本站其它相關文章!希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。