本文几个目的:
1。使用smtp库群发邮件
2。添加邮件的附件
3。将Excel附件添加到正文中
""" to_addr表示群发集,使用形如('abc.163.com,add.163.com,3243@qq.com') html表示要展示在正文中的网页或者表格等。 password字段表示邮箱的验证码,在打开smtp协议时记得,并不是邮箱的密码。 """
def send_email(to_addr,html):
from_addr = 'wangxingfan316@163.com'
password = '*********'
smtp_server = 'smtp.163.com'
# msg=MIMEText('hello,send by python...','plain','utf-8')
msg = MIMEMultipart('alternative')
msg['From'] = u'M10<wangxingfan316@163.com>'
to_addrs = to_addr.split(',')
msg['To'] = ','.join(to_addrs)
#msg['To'] = to_addr
msg['Subject'] = Header(time.strftime("%Y-%m-%d 自动化日报", time.localtime()), 'utf-8')
with open(filepath, 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('1', 'xlsx', filename='1.xlsx')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename='1.xlsx')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
msg.attach(MIMEText(html, 'html', 'utf-8'))
try:
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.starttls()
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
print('发送成功')
except smtplib.SMTPException:
print('发送失败')
""" filepath是Excel文件的地址 return的file就是html格式的,可以用于上个函数直接在邮箱附件主页中展示的。 """
def excel_to_html(filepath):
xd = pd.ExcelFile(filepath)
df = xd.parse()
with codecs.open('/Users/wangxingfan/Desktop/1.html', 'w', 'utf-8') as html_file:
html_file.write(df.to_html(header=True, index=False))
file = open('/Users/wangxingfan/Desktop/1.html').read()
return file