Python實現完整郵件
先上效果:
一、郵箱端設置
首先,要對郵件進行一下設置,在郵箱端獲取一個授權碼。
1、首先登錄網頁版126郵箱
2、打開 設置―POP3/SMTP/IMAP配置界面
3、新增一個授權碼
二、python發送郵件
1、安裝郵件模塊
pip install py-emails
2、調用模塊
引入郵箱模塊,配置收件人、發件人、授權碼等信息
#引入smtplib模塊 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage #配置郵箱信息 sender = '[email protected]' #發件人的地址 password = 'XXXXXXXXXXXX' #此處是我們剛剛在郵箱中獲取的授權碼 receivers = ['[email protected]', '[email protected]'] #郵件接受方郵箱地址,可以配置多個,實現群發
3、設置郵件內容
#郵件內容設置 message = MIMEText('你好呀,王思聰~~~','plain','utf-8') #郵件標題設置 message['Subject'] = '來自CSDN的問候' #發件人信息 message['From'] = sender #收件人信息 message['To'] = receivers[0] #通過授權碼,登錄郵箱,并發送郵件 try: server = smtplib.SMTP('smtp.126.com') #配置126郵箱的smtp服務器地址 server.login(sender,password) server.sendmail(sender, receivers, message.as_string()) print('發送成功') server.quit() except smtplib.SMTPException as e: print('error',e)
4、添加附件
另外,我們發送郵件時,經常需要添加各式各樣的附件。python同樣可以實現。
如下,我們可以通過代碼添加圖片、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讀取郵件
通過我們設置的授權碼,登錄郵箱賬號,獲取該賬號收到的郵件內容。
首先安裝zmail模塊
pip install zmail
讀取郵件
server = zmail.server('[email protected]','授權碼') mail = server.get_latest() zmail.show(mail)
獲取郵件效果如下:
------------------------- Subject 來自lex的python自動發送郵件 Id 4 From [email protected] To None Date 2021-07-15 10:18:39+08:00 Content_text ['來自lex的python自動發送郵件'] 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行代碼實現完整郵件功能 的詳細內容,更多關于Python實現完整郵件的資料請關注服務器之家其它相關文章!希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_42350212/article/details/118751583