發郵件是一種很常見的操作,本篇主要介紹一下如何用python實作自動發件,
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from email.mime.image import MIMEImage import time mail_host="smtp.126.com" mail_user="[email protected]" mail_pass="******"#注意如果郵箱開啟了授權碼,此處要填寫授權碼,否則會報smtplib.SMTPAuthenticationError: (535, b'Error: authentication failed') sender="[email protected]" receiver = ['郵箱1','郵箱2']#群發郵件 for i in range(n):#自定義回圈發多少遍 try: message = MIMEMultipart() message["From"] = Header(sender) message["To"] = ','.join(receiver) message["Subject"] = Header("主題", "utf-8").encode()#主題 message.attach(MIMEText("正文", "plain", "utf-8"))#正文 """ 定附件 """ att = MIMEText(open(r'C:\Users\Administrator\Desktop\1.txt').read(), "base64", "utf-8") att["Content-Type"] = 'application/octet-stream' att.add_header("Content-Disposition", 'attachment', filename="1.txt")#這一步可避免檔案不能正常打開 message.attach(att) """ 構造圖片(以附件形式上傳) """ image = MIMEImage(open(r'C:\Users\Administrator\Desktop\1.jpg', 'rb').read()) image.add_header('Content-ID', '<image1>')#可避免圖片不能正常打開 image["Content-Disposition"] = 'attachment; filename="picture.jpg"' message.attach(image) """ 發送郵件 """ smtp = smtplib.SMTP_SSL(host=mail_host) smtp.connect(host=mail_host, port=465) smtp.login(mail_user, mail_pass) smtp.sendmail(sender, message['To'].split(','), message.as_string()) print("在%s第" % ctime(), str(i+1), "封郵件發送") smtp.quit() except smtplib.SMTPException as e: raise e
最終實作
本文首發于python黑洞網,博客園同步更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/5968.html
標籤:Python
下一篇:python計算年收益
