# coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
def send_mail(username, password, receivers, title, content, host="smtp.163.com"):
# 构造邮件
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = formataddr(["迷心兔", username])
msg['To'] = receivers
msg['Subject'] = Header(title, 'utf-8')
# 发送邮件
try:
# 1.建立和SMTP邮件服务器的连接
smtp = smtplib.SMTP_SSL(host, 465, timeout = 2)
# 1.建立和SMTP邮件本地的连接
# smtp = smtplib.SMTP(host, 25)
# 2.打印出和SMTP服务器交互的所有信息
# smtp.set_debuglevel(1)
# 3.发送者的邮箱账号,密码
smtp.login(username, password)
# 4.参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.sendmail(username, receivers, msg.as_string( ))
# 5.发送完毕后退出smtp
smtp.quit( )
print('发送成功')
except smtplib.SMTPException as e:
print(e)
if __name__ == '__main__':
username = "***@163.com" # 发送者账号
password = "***" # 口令或密码
receivers = "***@qq.com" # 接收者账号列表
title = "主题:***" # 邮件主题
content = "内容为: ***" # 邮件内容
send_mail(username, password, receivers, title, content)
发送纯文本邮件
最新推荐文章于 2022-08-27 21:14:34 发布