首頁>技術>

python傳送郵件並帶有附件,如果安裝相關的包,先用pip安裝這些包:smtplib,emailimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplication   # msg,郵件的正文 def send_mail(msg):     # 設定郵件伺服器,請按實際情況修改     mail_host = "smtp.xxx.com.cn"     # 登入郵件的帳號,請按實際情況修改     mail_user = "test"     # 登入郵件的密碼,請按實際情況修改     mail_pass = "test123456"     # 傳送人,請按實際情況修改     sender = '[email protected]'     # 接收人,,請按實際情況修改,多個接收人以逗號隔開     receivers = ['[email protected]', '[email protected]']     # msg = MIMEMultipart('mixed')     msg = MIMEMultipart('related')     # 郵件標題,請按實際修改     msg['Subject'] = u"這裡是郵件的標題 "     msg['From'] = sender     # 收件人為多個收件人,透過join將列表轉換為以;為間隔的字串     msg['To'] = ";".join(receivers)      # 設定郵件正文     html_msg = msg     text_plain = MIMEText(html_msg, 'html', 'utf-8')     msg.attach(text_plain)      # 設定附件,file_path是附件的路徑,請按實際情況修改     file_path = "d:\\test.html"     sendfile = MIMEApplication(open(file_path, 'rb').read())     sendfile.add_header('Content-Disposition', 'attachment', filename='fail-report.html')     msg.attach(sendfile)      try:         smtpObj = smtplib.SMTP()         smtpObj.connect(mail_host)         smtpObj.login(mail_user, mail_pass)         smtpObj.sendmail(sender, receivers, msg.as_string())         print ("郵件傳送成功")     except smtplib.SMTPException:         print ("郵件傳送失敗")

15
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 輪詢MODBUS通訊指令案例