1 # coding: utf-8
 2 
 3 import smtplib
 4 from email.mime.multipart import MIMEMultipart
 5 from email.mime.text import MIMEText
 6 from email.header import Header
 7 import re
 8 
 9 
10 def e_mail(smtpserver ='smtp.163.com',
11            username='自己邮箱账号',
12            password='自己邮箱授权码',
13            receiver='目标邮箱地址',
14            subject='邮件主题',
15            text='邮件内容',
16            sendfiles=None,   # 附件
17            ):
18 
19     """
20             此函数用以发送邮件
21         参数说明:smtpserver为smtp服务器
22                  username为发送者邮箱用户名
23                  password为发送者邮箱密码/授权码
24                  receiver为接收者邮箱(可以有多个,用','分隔)
25                  subject为邮件主题
26                  text为邮件内容
27                  sendfiles为附件路径(可以有多个,用','分隔)
28         注:所有参数均为字符串类型
29 
30     """
31 
32     # 发件人
33     sender = username
34 
35     # 收件人(可以为多个收件人)
36     # receivers = ['aaakkkbbbaaa2@163.com', 'liwei@staff.cntv.cn']
37     receivers = []
38     for i in receiver.split(','):
39         receivers.append(i)
40 
41     # 邮件标题
42     subject = Header(subject, 'utf-8').encode()
43 
44     # 邮件内容
45     main_body = text
46 
47     # 构造邮件对象
48     msg = MIMEMultipart('mixed')
49 
50     # 将邮件标题、发件人、收件人加入邮件对象。
51     msg['Subject'] = subject
52     msg['From'] = '%s <%s>' % (username, username)
53     # msg['To'] = 'XXX@126.com'
54     # 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
55     msg['To'] = ";".join(receivers)
56     # msg['Date']='2012-3-16'
57 
58     # 将邮件内容加入邮件对象
59     if text:
60         # 编码文字内容
61         text_plain = MIMEText(main_body, 'plain', 'utf-8')
62         # 将文字内容加入邮件对象
63         msg.attach(text_plain)
64 
65     # 将附件加入邮件对象
66     if sendfiles:
67         # 遍历所有附件
68         for i in sendfiles.split(','):
69             # 加载附件
70             sendfile = open(r'%s' % i, 'rb')
71             sendfile = sendfile.read()
72             text_att = MIMEText(sendfile, 'base64', 'utf-8')
73             text_att["Content-Type"] = 'application/octet-stream'
74             # 为附件命名
75             try:
76                 file_name = re.match(r'.*[\\/](.*)$', i).group(1)
77             except AttributeError:
78                 file_name = i
79             text_att.add_header('Content-Disposition', 'attachment', filename=file_name)
80             # 将附件加入邮件对象
81             msg.attach(text_att)
82 
83     # 发送邮件
84     smtp = smtplib.SMTP()
85     smtp.connect(smtpserver)
86     # 用set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息。
87     # smtp.set_debuglevel(1)
88     smtp.login(username, password)
89     smtp.sendmail(sender, receivers, msg.as_string())
90     smtp.quit()
91     return '邮件发送完毕'
92 
93 
94 if __name__ == '__main__':
95     e_mail(sendfiles=r'C:\Users\Administrator\Desktop\结果.png,C:\Users\Administrator\Desktop\Agent说明文档.txt')

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。