1. 程式人生 > >python 發郵件,帶附件,中文

python 發郵件,帶附件,中文

 

 

# !/usr/bin/python
# -*- coding: UTF-8 -*-
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr

import cv2
import os
import smtplib
import urllib
from email.mime.text import MIMEText
from email.header import Header

sender = '
[email protected]
' mail_user ='[email protected]' receivers = [] # 接收郵件,可設定為你的QQ郵箱或者其他郵箱 # 第三方 SMTP 服務 mail_host = "smtp.sibaida.com" # 設定伺服器 receivers.append("[email protected]") # 使用者名稱 mail_pass = "Sibaida123456" # 口令 def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def sendMsa(subject,content): try: msg = MIMEMultipart() message = MIMEText(content, 'plain', 'utf-8') msg.attach(message) # msg['From'] = Header("思百達物聯-攝像頭異常通知-"+sender, 'utf-8') msg['From'] = _format_addr('思百達物聯 <%s>' % sender) # message['To'] = Header("監控平臺異常", 'utf-8') msg['Subject'] = Header(subject, 'utf-8') img_url='d:/bgs.jpg' with open(img_url, 'rb') as f: # 設定附件的MIME和檔名,這裡是jpg型別: mime = MIMEBase('image', 'jpg', filename='zhuapai.jpg') # 加上必要的頭資訊: mime.add_header('Content-Disposition', 'attachment', filename='zhuapai.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的內容讀進來: mime.set_payload(f.read()) # 用Base64編碼: encoders.encode_base64(mime) # 新增到MIMEMultipart: msg.attach(mime) smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 為 SMTP 埠號 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, msg.as_string()) print("郵件傳送成功") except smtplib.SMTPException as e: print("Error:",e.__cause__) sendMsa("郵件標題","郵件內容")