发送带有正文以及附件的邮件

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

下面是在邮件里面,正文显示 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()

 

posted @ 2016-04-08 16:53  微微微笑  阅读(2708)  评论(0编辑  收藏  举报