本帖最后由 suchocolate 于 2021-7-20 15:16 编辑
https://www.runoob.com/python3/python3-smtp.html
上面是教程,下面是根据你的需求写的案例:#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import time
def send(receiver, m):
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("邮件里发件人名称", 'utf-8')
message['To'] = Header("邮件里收件人名称", 'utf-8')
subject = '邮件标题'
message['Subject'] = Header(subject, 'utf-8')
# 邮件正文内容
message.attach(MIMEText(m[0], 'plain', 'utf-8')) # m[0]是邮件正文
# 构造附件,传送当前目录下的 file 文件
att1 = MIMEText(open(m[1], 'rb').read(), 'base64', 'utf-8') # m[1]是邮件附件的名称
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = f'attachment; filename="{file}"'
message.attach(att1)
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, [receiver], message.as_string())
print("邮件发送成功")
except Exception as e:
print(e)
if __name__ == "__main__":
mail_host = "smtp.qq.com" # qq邮箱发件服务器域名,不用改
mail_user = "your_mail@qq.com" # 你的qq邮箱
mail_pass = "your_authorization_code" # qq邮箱给的授权码
sender = 'your_mail@qq.com' # 你的qq邮箱
receivers = {'receive_1@qq.com': ['正文1', 'test1.txt'],
'receive_2@sohu.com': ['正文2', 'test2.txt'],
'receive_3@163.com': ['正文3', 'test3.txt']} # 收件人与正文和附件对应关系
while True: # 循环
ct = time.localtime(time.time()) # 查看当前时间
if ct[3] == 17 and ct[4] == 30: # 当17:30的时候,给3个接受者发送邮件
for k, v in receivers.items():
send(k, v)
time.sleep(59) # 如果不是17:30,程序休眠
|