python調用smtp發送郵件(多個收件人)


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


def send_email(file_name):
    '''發送測試報告'''
    try:
        From = "send@xxx.com" 
        To = "recieved@xx.com,recieved2@xx.com" 
        
        source = '..//Report//' + file_name
        
        server = smtplib.SMTP("smtp.xxx.com") 
        server.login("send@xxx.com","password") #僅smtp服務器需要驗證時 
        
        # 構造MIMEMultipart對象做為根容器 
        main_msg = MIMEMultipart() 
        
        # 構造MIMEText對象做為郵件顯示內容並附加到根容器 
        text_msg = MIMEText("xx自動化測試報告!") 
        main_msg.attach(text_msg) 
        
        # 構造MIMEBase對象做為文件附件內容並附加到根容器 
        contype = 'application/octet-stream' 
        maintype, subtype = contype.split('/', 1) 
        
        # 讀入文件內容並格式化 
        data = open(source, 'rb') 
        file_msg = MIMEBase(maintype, subtype) 
        file_msg.set_payload(data.read( )) 
        data.close( ) 
        encoders.encode_base64(file_msg) 
        
        # 設置附件頭 
        basename = os.path.basename(source)
        #解決中文附件名亂碼問題 
        file_msg.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename)) 
        main_msg.attach(file_msg) 
        
        # 設置根容器屬性 
        main_msg['From'] = From 
        main_msg['To'] = To 
        main_msg['Subject'] = Header("XX自動化測試報告","utf-8")
        main_msg['Date'] = formatdate( ) 
        
        # 得到格式化后的完整文本 
        fullText = main_msg.as_string( ) 
        
        # 用smtp發送郵件 
        try: 
            server.sendmail(From, To.split(','), fullText) 
        finally: 
            server.quit()
    except Exception:
        logger.exception('發送郵件出錯!')

 


免責聲明!

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



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