发邮件是一种很常见的操作,本篇主要介绍一下如何用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="xxx@126.com"
mail_pass="******"
sender="xxx@126.com"
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
最终实现