前言

这里记录一下通过smtp服务使用python发送邮件到163邮箱的小例子。

代码

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
37
38
39
40
41
42
43
44
45
46
47
48
49
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 网易邮箱SMTP服务器配置
smtp_server = "smtp.163.com"
port = 465 # 对于SSL
sender_email = "liaozhangsheng@163.com" # 你的网易邮箱地址
password = "yourSecretKey" # 你的邮箱密码或应用专用密码
receiver_email = "2087628670@qq.com" # 收件人邮箱地址

# 创建邮件主体
message = MIMEMultipart("alternative")
message["Subject"] = "Python SMTP 邮件测试(网易邮箱)"
message["From"] = sender_email
message["To"] = receiver_email

# 创建邮件文本
text = """\
你好,
这是一封通过Python和网易邮箱发送的测试邮件。\n
"""

html = """\
<html>
<body>
<p>你好,<br>
这是一封通过Python和网易邮箱发送的测试邮件。<br>
</p>
</body>
</html>
"""

# 将文本和HTML版本加入邮件主体
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

message.attach(part1)
message.attach(part2)

try:
# 连接到SMTP服务器并发送邮件
with smtplib.SMTP_SSL(smtp_server, port) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
print("邮件发送成功")
except Exception as e:
print(f"邮件发送失败: {e}")