站內搜尋:Yahoo搜尋的結果,如果沒有給完整的網址,請在站內再搜尋一次!

2019-07-31

使用Python smtplib 透過GMail的SMTP傳送中文編碼(UTF8 / base64)的電子郵件

郵件發送的程式碼

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#from email.mime.image import MIMEImage
from email.header import Header

zUser="login_account@gmail.com"
zPass="LoginPassword"
zFrom="郵件通知<Sender@bod.idv.tw>"
zTo=["Receiver@gmail.com"]
#多個收件人
#zTo=['[addr1@mailserver]','[addr2@mailserver]',...]
#mail with name : toName<addr@mailserver>
#mail to many : toName1<addr1@mailserver>;toName2<addr2@mailserver>;...
#
#使用Header物件對中文內容進行utf-8和Base64進行編碼
zSubject = '測試中文標題 郵件發送 utf8/base64 編碼'
zSubject=Header(zSubject, 'utf-8').encode()

#組合郵件物件 MIMEMultipart
#郵件標題、送件人,收件人,發送日期
oMsg = MIMEMultipart('mixed')
oMsg['Subject'] = zSubject
oMsg['From'] = zFrom
##多個收件人 ['[addr1@mailserver]','[addr2@mailserver]',...]
##可用join將列表轉換為用;為間隔的字串
oMsg['To'] = ";".join(zTo)
oMsg['Date']='2019-07-31'

##郵件內容(純文字:plain)
#zText = "Line 1 : 中文第1行\nLine 2 : 中文第2行\nLine 3 : 中文第3行\n"
#zText = MIMEText(zText,'plain', 'utf-8')
#oMsg.attach(zText)

##郵件內容(HTML)
zHtml = """
<html><head></head>
  <body>
    <p>中文內容測試<br>連結網址 : <a href="http://books.bod.idv.tw">bod-idv-tw的網址</a></p>
  </body>
</html>
"""
zHtml = MIMEText(zHtml,'html', 'utf-8')
#把HTML郵件內容,包成.html檔案,附為電子郵件的附件
#zHtml["Content-Disposition"] = 'attachment; filename="mailContent.html"'
oMsg.attach(zHtml)

#傳送郵件
oSmtp=smtplib.SMTP('smtp.gmail.com',587)
oSmtp.starttls()
oSmtp.ehlo()
oSmtp.login(zUser,zPass)
oSmtp.sendmail(zFrom, zTo, oMsg.as_string())
oSmtp.quit()

參考資料: https://www.itread01.com/content/1543857361.html

沒有留言:

張貼留言