Python自动化必备发送邮件报告脚本详解

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
import smtplib
#smtplib库主要用来连接第三方smtp库,用来发邮件
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
#email库主要用来定义邮件的格式,发送人,接收人,邮件标题,邮件正文


smtp_server = 'smtp.163.com'
smtp_user = '185xxxxx@163.com'
smtp_pwd = 'xxxxxxx'
#user和pwd是用来连接smtp.163.com,不是邮箱的密码。需要在邮箱里设置一下。
sender = smtp_user
#发送人
receivers = ["xxxxxx", "xxxxxxx"]
#接收邮件的邮箱列表

msg = MIMEMultipart()
#创建MIMEMultipart()实例,用于构建附件

msg['From'] = Header('张xx<18519xxxxx>', 'utf-8')
subject = 'Python final Mail'
msg['Subject'] = Header(subject, 'utf-8')
#创建邮件的发送人和主题

with open('mail.html', 'r', encoding='UTF-8') as fp:
mail_msg = fp.read()
msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
#读取mail.html文件,发送html文本

att1 = MIMEText(open('mail1.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="mail1.txt"'
msg.attach(att1)
#创建附件1

att2 = MIMEText(open('runoob.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="runoob.txt"'
msg.attach(att2)
#创建附件2

sm = smtplib.SMTP()
sm.connect(smtp_server, 25)
sm.login(smtp_user, smtp_pwd)
#连接smtp服务器,并登陆

try:
for rec in receivers:
msg['To'] = rec
sm.sendmail(sender, rec, msg.as_string())
#发送邮件
print("Send mail to {0} succeed".format(rec))
except smtplib.SMTPException:
print("Send mail to {0} fail".format(rec))
sm.quit()
#关闭连接

转载于:https://www.cnblogs.com/william126/p/8892941.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值