使用python SSL SMTP 发送邮件
以163 SSL SMTP服务为例:163开通SMTP服务和获取授权码
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import traceback
# 第三方 SMTP 服务
SENDER = "xxxxx@163.com" # 用户名
MAIL_PASS = "XXXXXXXXXXXXXX" # 授权码,需要手动申请,
RECEIVERS_LIST = ['xxxxxx@163.com', 'xxxxxxx@qq.com'] # 邮件收件人
def send_mail(mail_content: str, subject: str, smtp_server_addr: str = "smtp.163.com", smtp_server_port: int = 465,
sender=SENDER, mail_pass=MAIL_PASS, receivers_list=None):
"""
发送邮件接口,默认发送到163邮件
:param receivers_list: 邮件接收列表,eg:['xxxx@qq.com', 'ttttt@qq.com']
:param mail_pass: 密钥
:param sender: 发送邮件人
:param mail_content: 邮件内容
:param subject: 邮件主题
:param smtp_server_addr: 默认163 smtp地址
:param smtp_server_port: 默认163 smtp ssl端口
:return: True表示成功,False表示失败
"""
if receivers_list is None:
receivers_list = RECEIVERS_LIST
try:
msg = MIMEText(mail_content, 'plain', 'utf-8')
msg['From'] = formataddr((sender.split('@')[0], sender)) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] = ','.join([formataddr((receiver.split('@')[0], receiver))
for receiver in receivers_list]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
msg['Subject'] = subject # 邮件的主题,也可以说是标题
server = smtplib.SMTP_SSL(smtp_server_addr, smtp_server_port) # 发件人邮箱中的SMTP服务器,端口是25
server.login(sender, mail_pass) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(sender, receivers_list, msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
return True
except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False
traceback.print_exc()
return False
if __name__ == '__main__':
if send_mail(subject="xxxx", content="xxx"):
print('发送成功!')
else:
print('发送失败!')