1. 程式人生 > >python 自動發郵件

python 自動發郵件

一、一般發郵件的方法

Python對SMTP支援有smtplib和email兩個模組,email負責構造郵件,smtplib負責傳送郵件。

注意到構造MIMETEXT物件時,第一個引數就是郵件正文,第二個引數是MIME的subtype,傳入'plain'表示純文字,最終的MIME就是‘text/plain’,最後一定要用utf-8編碼保證多語言相容性。

然後,通過SMTP發出去:

 1 # coding:utf-8
 2 import smtplib
 3 from email.mime.text import MIMEText
 4 
 5 
 6 class SendMail:
7 8 def send_mail(self, receiver_list, sub, content): 9 host = "smtp.qq.com" # 伺服器地址 10 sender = "123@qq.com" # 發件地址 11 password = "pwd" 12 #郵件內容 13 message = MIMEText(content, _subtype='plain', _charset='utf-8') 14 message['Subject
'] = sub # 郵件主題 15 message['From'] = sender 16 message['To'] = ";".join(receiver_list) # 收件人之間以;分割 17 server = smtplib.SMTP() 18 # 連線伺服器 19 server.connect(host=host) 20 # 登入 21 server.login(user=sender, password=password) 22 server.sendmail(from_addr=sender, to_addrs=receiver_list, msg=message.as_string())
23 server.close() 24 25 if __name__ == '__main__': 26 send = SendMail() 27 receive = ["123qq.com", "[email protected]"] 28 sub = "測試郵件" 29 content = "測試郵件" 30 send.send_mail(receive, sub, content)

其實,這段程式碼也並不複雜,只要你理解使用過郵箱傳送郵件,那麼以下問題是你必須要考慮的:

  • 你登入的郵箱帳號/密碼
  • 對方的郵箱帳號
  • 郵件內容(標題,正文,附件)
  • 郵箱伺服器(SMTP.xxx.com/pop3.xxx.com)

 

二、利用yagmail庫傳送郵件

yagmail 可以更簡單的來實現自動發郵件功能。

首先需要安裝庫: pip install yagmail

然後:

 1 import yagmail
 2 
 3 
 4 class SendMail:
 5 
 6     def send_mail(self, receiver_list, sub, content, attach=None):
 7         host = "smtp.qq.com"
 8         sender = "[email protected]"
 9         password = "ryprfozwyqawbgfg"
10         # 連線伺服器
11         yag = yagmail.SMTP(user=sender, password=password, host=host)
12         # 郵件內容
13         yag.send(to=receiver_list, subject=sub, contents=content, attachments=attach)
14 
15 
16 if __name__ == '__main__':
17     send = SendMail()
18     receive = ["[email protected]", "[email protected]"]
19     sub = "測試郵件"
20     content = ["yagmail測試郵件", "\n", "hello word"]
21     attch = "C:\\Users\\Administrator\\Desktop\\10.jpg"
22     send.send_mail(receive, sub, content, attch)

 

另外,附件也可以之間寫在content中,即conten = ["yagmail測試郵件", "\n", "hello word", "C:\\Users\\Administrator\\Desktop\\10.jpg"]

少寫了好幾行程式碼