python发送邮件

Uncategorized
399 words

当我们在深度学习训练时,可以将训练的结果通过邮箱发送给自己,以便及时查看训练结果。

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
# smtplib 用于邮件的发信动作
import smtplib
# email 用于构建邮件内容
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
# 构建邮件头
from email.header import Header
import base64

# path = r'xxx'
def send(path):
# 发信方的信息:发信邮箱,QQ 邮箱授权码
from_addr = '@qq.com'
password = ''
# 收信方邮箱
to_addr = '@qq.com'
# 发信服务器
smtp_server = 'smtp.qq.com'

html_msg = """
<p>Python 邮件发送HTML格式文件测试...</p>
"""


# 创建一个带附件的实例msg
msg = MIMEMultipart()

msg['To'] = Header('李四') # 接收者
msg['From'] = Header(f'=?utf-8?B?{base64.b64encode("python自动发送".encode()).decode()}=?= <@qq.com>') #必须填发送者邮箱
subject = 'Python SMTP 邮件测试'
msg['Subject'] = Header(subject, 'utf-8') # 邮件主题
# 邮件正文内容
msg.attach(MIMEText(html_msg, 'html', 'utf-8'))


# # 构造附件,传送当前目录下的 test1.txt 文件
# att1 = MIMEText(open('test1.txt', 'rb').read(), 'base64', 'utf-8')
# att1["Content-Type"] = 'application/octet-stream'
# # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
# att1["Content-Disposition"] = 'attachment; filename="test1.txt"'
# msg.attach(att1)


# 添加图片附件
imageFile = path
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
msg.attach(imageApart)


try:
smtpobj = smtplib.SMTP_SSL(smtp_server)
smtpobj.connect(smtp_server, 465) # 建立连接--qq邮箱服务和端口号
smtpobj.login(from_addr, password) # 登录--发送者账号和口令
smtpobj.sendmail(from_addr, to_addr, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("无法发送邮件")
finally:
# 关闭服务器
smtpobj.quit()

在训练的代码中加入

1
2
3
4
5
6
from sendemail import send


# 训练结束发送QQ邮件
path = r'xxx'
send(path) # 这个path就只是一张图片的路径