自定義了一個email模塊,符合大多數人的使用習慣

 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')
相關文章
相關標籤/搜索