python发送邮件demo
# 1、先导入相关的库和方法
import smtplib
import email
# 负责构造文本
from email.mime.text import MIMEText
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
# 进度条
from tqdm import tqdm
def print_pbar(index):
pbar = tqdm(8, desc="发送邮件进度")
pbar.update(index)
pbar.close()
# 2、设置邮箱域名、发件人邮箱、邮箱授权码、收件人邮箱
# SMTP服务器
mail_host = "smtp.gmail.com"
# 发件人邮箱
mail_sender = "test@gmail.com"
# 如果开启了邮箱授权码,就要用邮箱授权码,负责是邮箱密码,如何获取邮箱授权码,请看本文最后教程
mail_license = "***********************"
# 收件人邮箱,可以为多个收件人
mail_receivers = ["******@qq.com","******@outlook.com"]
print_pbar(2)
# 3、构建MIMEMultipart对象代表邮件本身,可以往里面添加文本、图片、附件等
mm = MIMEMultipart('related')
print_pbar(3)
# 4、设置邮件头部内容
# 邮件主题
subject_content = """Python邮件测试17"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = mail_sender
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱,如果是多个,则自己改改接收者,遍历拼接赋值就OK了
mm["To"] = mail_receivers[0]
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')
print_pbar(4)
# 5、添加正文文本
# 邮件正文内容
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)
print_pbar(5)
# 6、添加图片
file = "a.jpg"
atta = MIMEApplication(open(file, 'rb').read())
# 设置附件信息
atta.add_header('Content-Disposition', 'attachment', filename=file)
# 添加附件到邮件信息当中去
mm.attach(atta)
print_pbar(6)
# 7、添加附件(excel表格)
# 构造附件
file = "仓库打印机模板.xls"
atta = MIMEApplication(open(file, 'rb').read())
# 设置附件信息
atta.add_header('Content-Disposition', 'attachment', filename=file)
# 添加附件到邮件信息当中去
mm.attach(atta)
print_pbar(7)
# 8、发送邮件
# 创建SMTP对象
# 设置发件人邮箱的域名和端口,端口地址为587
stp = smtplib.SMTP_SSL(mail_host,465)
stp.ehlo()
stp.set_debuglevel(1)
print_pbar(8)
try:
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender,mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
# 关闭SMTP对象
stp.quit()
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
参考资料: 参考: 飘逸的python - 发送带各种类型附件的邮件_mattkang-CSDN博客_python 发邮件,除了mimeapplication还有啥 https://blog.csdn.net/u010180339/article/details/9811355
Python SMTP发送邮件 | 菜鸟教程 https://www.runoob.com/python/python-email.html
python 3.x - Python3 SMTP 'Connection unexpectedly closed' - Stack Overflow https://stackoverflow.com/questions/59179964/python3-smtp-connection-unexpectedly-closed
帮我改善此页面 (opens new window)
上次更新: 2021/02/16, 12:29:08