import argparse import smtplib, mimetypes from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email import utils from email import encoders from email.header import Header import os.path import datetime import time import sys # import plugs.FileHelper as fileHelper defaultencoding = 'utf-8' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) class SendMail(): startDate = '' def __init__(self, reportDate): startDate = reportDate print('初始化SendMail郵件,值爲:' + startDate) def SendMethod(self, startDate=None): print('SendMethod方法傳參的值爲:' + startDate) # 發送郵箱服務器 smtpserver = 'mail.qq.com' # smtpserver = 'smtp.163.com' 用smtplib.SMTP_SSL(smtpserver, 25) # 發送郵箱用戶名密碼 user = '[email protected]' password = 'test2018' # 發送和接收郵箱 sender = '[email protected]' receives = ['[email protected]', '[email protected]'] # ccs = ['[email protected]'] # 發送郵件主題和內容 subject = f'{startDate}_測試' content = f' <p> 您好~ </p> <p>附件爲{startDate}數據。</p><p> 請查收。 </p><p>謝謝~</p>' \ f'<br/><br/><br/><br/><p>From robot</>' # 構造附件內容:定義附件,構造附件內容 _rarUrl = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) + "\\test.zip" print('附件地址是abspath:' + _rarUrl) # _rarUrl2 = self.getsql(r"\test.rar") # 構建發送與接收信息] recc = receives + ccs msgRoot = MIMEMultipart() # 發送附件的方法定義爲一個變量 msgRoot.attach(MIMEText(content, 'html', 'UTF-8')) # 發送附件的方法中嵌套發送正文的方法 msgRoot['subject'] = subject msgRoot['From'] = sender msgRoot['To'] = ','.join(receives) msgRoot['Cc'] = ','.join(ccs) send_file = open(_rarUrl, 'rb').read() # 'rb'表示r讀取,b表示二進制方式讀取 att = MIMEText(send_file, 'base64', 'utf-8') # 調用傳送附件模塊,傳送附件 send_file #att = MIMEApplication(send_file) #用MIMEApplication 就不能有 base64和utf-8 att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = f'attachment; filename={startDate}月測試.zip' #att.add_header('Content-Disposition', 'attachment', filename=f'{startDate}月測試.zip') msgRoot.attach(att) # 添加附件到正文中 print("Start 登錄服務器.") # SSL協議端口號要使用25 smtp = smtplib.SMTP(smtpserver, 25) # _SSL print("Start 向服務器標識用戶身份.") # HELO 向服務器標識用戶身份 smtp.helo(smtpserver) print("Start 服務器返回結果確認.") # 服務器返回結果確認 smtp.ehlo(smtpserver) print("Start 登錄郵箱服務器用戶名和密碼.") try : # 登錄郵箱服務器用戶名和密碼 smtp.login(user, password) print("Start send email...") smtp.sendmail(sender, recc, msgRoot.as_string()) smtp.quit() print("Send End!") except smtplib.SMTPException as e: print('error:',e) #打印錯誤