Python sendemail txt,html,图片及附件

上代码

from email.mime.image import MIMEImage

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.utils import parseaddr,formataddr
import smtplib

"""发送附件图片"""
"""
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


#邮件配置参数
From_addr = xx@xx.com"
Password = "xx"
To_addr = "xx"
Smtp_server = "smtp.exmail.qq.com"
###


def send_mail_file(file_new,file_txt,file_png):
    """发送带附件的邮件"""
    print('正在发送中-------------------------')
    # 读取html报告文件内容
    with open(file_new, 'rb') as f:
        mail_body = f.read()

    # 邮件内容封装
    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    #带附件
    msg=MIMEMultipart()

    # 邮件对象
    msg['From'] = _format_addr('测试负责人 <%s>' % from_addr)
    msg['To'] = _format_addr('管理员 <%s>' % to_addr)
    msg['Subject'] = Header('测试机', 'utf-8').encode()
    msg['Date'] = "2020-3-25"

    #txt
    text="hi,this is txt,thanks!"
    text_plain=MIMEText(text,"plain","utf-8")
    msg.attach(text_plain)

    #image
    sendimagefile=open(file_png,'rb').read()
    image=MIMEImage(sendimagefile)
    image.add_header('Content-ID','<image1>')
    image.add_header('Content-Disposition', 'attachment', filename=file_png)
    msg.attach(image)

    #html
    text_html=MIMEText(mail_body,'html','utf-8')
    msg.attach(text_html)

    #MIMEBase标识附件的对象
    att=MIMEText(mail_body,'base64','utf-8')
    att.add_header('Content-Disposition', 'attachment', filename=file_new)
    msg.attach(att)

    #附件
    sendfile=open(file_txt,'rb').read()
    text_att=MIMEText(sendfile,'base64','utf-8')
    text_att['Content-Type']='application/octet-stream'

    text_att.add_header('Content-Disposition', 'attachment', filename=file_txt)
    msg.attach(text_att)

    # 发送邮件
    server = smtplib.SMTP(smtp_server, 25)
    # server.set_debuglevel(1)   #打印信息
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
    print("邮件已发出!注意查收。")

if __name__=="__main__":
    file_new=r"F:/download/report/report.html"
    file_png=r"F:/download/test.png"
    file_txt=r"F:/download/txt.txt"

    send_mail_file(file_new, file_txt, file_png)

 

posted @ 2020-03-25 19:37  Golover  阅读(326)  评论(0编辑  收藏  举报