您的位置:首页 > 编程语言 > Python开发

python自动化email发送和添加附件

2017-12-29 14:23 323 查看

#-*- coding:utf-8 -*-

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

import smtplib

import os

import time

# 发送邮箱

sender = "xxxxxxxx@163.com"

# 接收邮箱

receiver = "xxxxxxxxxxxx@qq.com"

# 发送邮件服务器

smtpserver = "smtp.163.com"

# 发送邮箱账号和密码

username = "xxxxxxxxxx@163.com"

password = "xxxxxxxxx"

# filename

filename = os.getcwd() +"/jd.html"

# 读取测试报告的内容

with open(filename, "rb") as f:

    mail_body = f.read()

#定义邮件内容

msg = MIMEMultipart()

body = MIMEText(mail_body,_subtype='html', _charset='utf-8')

msg['Subject'] = u"自动化报告"

msg['from'] = sender

msg['to'] = receiver

#加上时间戳

msg["date"] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

msg.attach(body)

#添加附件

att = MIMEText(open(filename).read(), "base64", "gbk")

att["Content-Type"] = "application/octet-stream"

att["Content-Disposition"] = 'attachment; filename= "jd.html"'

msg.attach(att)

#登录邮箱

smtp = smtplib.SMTP()

#连接邮箱服务器

smtp.connect(smtpserver)

#用户名密码

smtp.login(username, password)

smtp.sendmail(sender, receiver, msg.as_string())

smtp.quit()

print ('邮件已发送至对应账号!!')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: