本文为SMTP邮件投递代码调用示例,适用于Python3.6及以上。
阿里邮箱配置
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('邮件发送成功!')