SMTP郵件投遞代碼之Python3.6及以上調(diào)用示例
更新時(shí)間:
本文為SMTP郵件投遞代碼調(diào)用示例,適用于Python3.6及以上。
阿里郵箱配置
SMTP服務(wù)器地址:smtp.mxhichina.com或smtp.qiye.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.utils import formataddr
'''~~~smtp認(rèn)證使用的郵箱賬號(hào)密碼~~~'''
username = ''
password = ''
'''~~~定義發(fā)件地址~~~'''
From = formataddr(['','']) #昵稱(郵箱沒有設(shè)置外發(fā)指定自定義昵稱時(shí)有效)+發(fā)信地址(或代發(fā))
replyto = '' #回信地址
'''定義收件對象'''
to = ','.join(['', '']) #收件人
cc = ','.join(['', '']) #抄送
bcc = ','.join(['', '']) #密送
rcptto = [to,cc,bcc] #完整的收件對象
'''定義主題'''
Subject = ''
'''~~~開始構(gòu)建message~~~'''
msg = MIMEMultipart('alternative')
'''1.1 收發(fā)件地址、回信地址、Message-id、發(fā)信時(shí)間、郵件主題'''
msg['From'] = From
msg['Reply-to'] = replyto
msg['TO'] = to
msg['Cc'] = cc
# msg['Bcc'] = bcc #建議密送地址在郵件頭中隱藏
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()
msg['Subject'] = Subject
''''1.2 正文text/plain部分'''
textplain = MIMEText('正文內(nèi)容', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)
'''1.3 封裝附件'''
file = r'C:\Users\yourname\Desktop\某文件夾\123.pdf' #指定本地文件,請換成自己實(shí)際需要的文件全路徑。
att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header("Content-Disposition", "attachment", filename='123.pdf')
msg.attach(att)
'''~~~開始連接驗(yàn)證服務(wù)~~~'''
try:
client = smtplib.SMTP_SSL('smtp.qiye.aliyun.com', 465)
print('smtp_ssl----連接服務(wù)器成功,現(xiàn)在開始檢查賬號(hào)密碼')
except Exception as e1:
client = smtplib.SMTP('smtp.qiye.aliyun.com', 25, timeout=5)
print('smtp----連接服務(wù)器成功,現(xiàn)在開始檢查賬號(hào)密碼')
except Exception as e2:
print('抱歉,連接服務(wù)超時(shí)')
exit(1)
try:
client.login(username, password)
print('賬密驗(yàn)證成功')
except:
print('抱歉,賬密驗(yàn)證失敗')
exit(1)
'''~~~發(fā)送郵件并結(jié)束任務(wù)~~~'''
client.sendmail(username, (','.join(rcptto)).split(','), msg.as_string())
client.quit()
print('郵件發(fā)送成功')
文檔內(nèi)容是否對您有幫助?