python3 发送邮件功能

本文最后更新于:2023年4月15日 下午

发信邮箱是腾讯企业邮箱。开发环境 Windows7。

主要使用smtplib来实现发邮件的功能。

简单的发送邮件功能

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
# 发送邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email():
fromaddr = "from1@your_email.com" # 你的发件邮箱
toaddr = "to1@your_email.com" # 目标邮箱
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"

body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.exmail.qq.com', 25) # 默认端口25
server.starttls()
server.login(fromaddr, "xxxx密码")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()


if __name__ == '__main__':
print('start sending email')
send_email()
print('end...')

邮件带上附件

Windows下注意文件路径的表达方式。

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
# 发送邮件
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send_email(from_email, pwd, target_email_list=[], attachment_file_list=[]):
"""
单独发送邮件
create on 2018-11-14
:param from_email: 源邮箱
:param pwd: 源邮箱密码
:param target_email_list: 目标邮件列表
:param attachment_file_list: 附件路径列表
:return: void
"""
if len(target_email_list) <= 0:
print('ERR: 目标邮件列表为空 -> 退出')
return

for target_email in target_email_list:
print('sending to ' + target_email)
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = target_email
msg['Subject'] = "更新"

body = '''尊敬的客户,
你好,请查收文件。
谢谢!
'''
msg.attach(MIMEText(body, 'plain'))

for file_path in attachment_file_list:
filename = str(file_path).split('\\')[-1]
print("file_path " + file_path + " filename: " + filename)
attachment = open(file_path, "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.exmail.qq.com', 25)
server.starttls()
server.login(from_email, pwd)
text = msg.as_string()
server.sendmail(from_email, target_email, text)
server.quit()


if __name__ == '__main__':
print('start sending email')
send_email(from_email="your_email.com",
pwd="密码",
target_email_list=["target1@foxmail.com", "target2@qq.com"],
attachment_file_list=[
r"E:\your_path.rar"])
print('end...')

参考:


python3 发送邮件功能
https://blog.rustfisher.com/2018/11/14/Python/python3-send-email/
作者
Rust Fisher
发布于
2018年11月14日
许可协议