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
| import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import traceback
my_sender = '发件人的邮箱地址'
my_passwd = '发件人的密码,网易、腾讯是用授权码'
my_user = '收件人的邮箱地址'
my_smtp_host='smtp.126.com' #126的smtp服务器地址
def mail():
ret = True
try:
#开始打包邮件
msg=MIMEMultipart()
msg['From']=formataddr(['发件人邮件昵称',my_sender])#设置发件人
msg['To'] = formataddr(['收件人邮件昵称',my_user])#设置收件人
msg['Subject']='这个是邮件的主题'
#下面是正文内容
pureText = MIMEText(open('release-notes.html', 'rb').read(),'html','utf-8')
#随便找的html文件,后面两个参数是告诉程序以html格式和utf-8字符
msg.attach(pureText)
#下面是各种类型的附件了
# 首先是xlsx类型的附件
xlsxpart = MIMEApplication(open('test.xlsx', 'rb').read())
xlsxpart.add_header('Content-Disposition', 'attachment', filename='test.xlsx')
msg.attach(xlsxpart)
# jpg类型的附件
jpgpart = MIMEApplication(open('2.jpg', 'rb').read())
jpgpart.add_header('Content-Disposition', 'attachment', filename='2.jpg')
msg.attach(jpgpart)
#下面开始发送了
server=smtplib.SMTP(my_smtp_host,25)#smtp服务器端口默认是25
# server.set_debuglevel(1)# 设置为调试模式,就是在会话过程中会有输出信息
server.login(my_sender,my_passwd)
server.sendmail(my_sender,[my_user,],msg.as_string())
server.quit()
except Exception :
ret = False
return ret
ret = mail()
if ret:
print("ok")
else:
print('failed')
|