【笔记】Python3发送邮件

前言

Python3通过SMTP协议发送邮件

发送文本邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
host = "smtp.qq.com"
port = 465
login_email = "aaaaaa@qq.com"
login_password = "xxxxxxxxxxxxxxxx"

send_from = "aaaaaa@qq.com"
send_to = "bbbbbb@qq.com"
email_subject = "主题"
email_content = "正文"

# 创建连接对象
#conn = smtplib.SMTP(host, port)
conn = smtplib.SMTP_SSL(host, port)

# 通过用户名和密码登录
conn.login(login_email, login_password)

# 配置邮件
msg = MIMEMultipart()
msg["Subject"] = Header(email_subject, "utf-8").encode()
msg["From"] = f"{send_from} <{send_from}>"
msg["To"] = send_to

# 插入文本内容
msg.attach(MIMEText(email_content, "plain", "utf-8"))

# 插入文件附件内容
#f = MIMEImage(open("<file>.zip", "rb").read())
#f["Content-Disposition"] = 'attachment; filename = "<file_name>.zip"'
#msg.attach(f)

# 发送邮件
conn.sendmail(send_from, send_to, msg.as_string())

# 关闭连接
conn.quit()

完成

参考文献

CSDN——酒坛坛儿^_^
哔哩哔哩——Python编程语言