發送帶有正文以及附件的郵件


為什么要寫下了呢? 因為本人找了好久,網上都是 “發送帶有正文的郵件”或者“發送帶有附件的郵件”。就沒見到一篇是“發送帶有正文+附件的郵件”。導致本人折騰這個折騰了好久,太浪費時間了。寫下來留作后續參考。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM