1. 程式人生 > 程式設計 >python實現郵件迴圈自動發件功能

python實現郵件迴圈自動發件功能

發郵件是一種很常見的操作,本篇主要介紹一下如何用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實現郵件迴圈自動發件功能的文章就介紹到這了,更多相關python郵件迴圈自動發件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!