本文為SMTP郵件投遞代碼調用樣本,適用於Python3.6及以上。
Alibaba Mail配置
SMTP伺服器位址:smtp.sg.aliyun.com
連接埠:非加密25,SSL加密465
# -*- coding:utf-8 -*-
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
# 寄件者郵箱地址
from email.utils import formataddr
username = ''
# 寄件者郵箱密碼
password = ''
# 自訂的回複地址
replyto = ''
From = formataddr(["自訂發信暱稱",'' ]) # 暱稱+發信地址(或代發)
to = ','.join(['', ''])
cc = ''
bcc = ''
# 收件者地址或是地址清單,支援多個收件者
rcptto = [to, cc, bcc]
#msg是郵件需要顯示的資訊
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('smtp發信測試')
msg['from'] = From
msg['rcptto'] = ','.join(rcptto)
print('收件列表:', msg['rcptto'], type(msg['rcptto']))
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()
# 構建alternative的text/plain部分
textplain = MIMEText('本郵件僅做測試', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)
# 構建alternative的text/html部分
texthtml = MIMEText('這是一封測試', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)
try:
client = smtplib.SMTP_SSL('smtp.sg.aliyun.com', 465)
print('服務和連接埠連通')
except:
print('服務和連接埠不通')
exit(1)
#開啟DEBUG模式
try:
client.set_debuglevel(0)
client.login(username, password)
print('賬密驗證成功')
except:
print('賬密驗證失敗')
exit(1)
client.sendmail(username, msg['rcptto'].split(','), msg.as_string())
client.quit()
print('郵件發送成功!')