zoukankan      html  css  js  c++  java
  • 发送带有正文以及附件的邮件

    为什么要写下了呢? 因为本人找了好久,网上都是 “发送带有正文的邮件”或者“发送带有附件的邮件”。就没见到一篇是“发送带有正文+附件的邮件”。导致本人折腾这个折腾了好久,太浪费时间了。写下来留作后续参考。

    下面是在邮件里面,正文显示 a.html内容,并且附件附上a.html。

    # coding: utf-8
    
    import smtplib
    from email.header import Header
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from os.path import basename
    
    def send_report():
        smtpserver = "smtp.xx.com"
        user = "user1"
        sender = "user1@xx.com"
        password = "pw1"
        receivers = "user1@xx.com;user2@xx.com"
    #     receivers_list = ['user1@xx.com','user2@xx.com']
    #     receivers=";".join(receivers_list)
        mail_subject='Send Email Test'
        send_file="a.html"
        
        send_mail(smtpserver, user, password, sender, receivers, mail_subject,send_file,send_file)
        
        print('Email has send out successfully!')
        
    def send_mail(smtpserver,user,password,sender,receivers,m_subject,m_content,m_attachment):
        
        msg=MIMEMultipart('alternative')
        msg['Subject']=Header(m_subject,'utf-8')
        msg['From']=sender
        msg['To']=receivers
        
        #mail content
        with open(m_content,"rb") as f:
            mail_content=f.read()
        msg.attach(MIMEText(mail_content,'html','utf-8'))
        
        #mail attachment
        with open(m_attachment,"rb") as f:
            mail_attach=f.read()
        send_attachment=MIMEText(mail_attach,'html','utf-8')
        send_attachment["Content-Type"]='application/octet-stream'
        send_attachment["Content-Disposition"]='attachment;filename='+basename(m_attachment)
        msg.attach(send_attachment)
        
        try:
            smtp=smtplib.SMTP()
            smtp.connect(smtpserver)
            smtp.login(user, password)
            smtp.sendmail(sender,receivers.split(";"),msg.as_string())
            smtp.quit()
        except Exception as e:
            print("Send Email Failed!!!")
            raise e
        
    if __name__ == "__main__":
        send_report()
  • 相关阅读:
    你可能不知道的 30 个 Python 语言的特点技巧
    正则替换sql为动态sql
    列表按指定个数分割后格式化输出
    多线程队列下载天涯帖子
    多线程下载图片
    sublime text3 运行python配置
    01_什么是接口测试
    02_Fiddler使用
    01_Fiddler安装
    05_功能测试
  • 原文地址:https://www.cnblogs.com/miniren/p/5368844.html
Copyright © 2011-2022 走看看