介紹
Zmail 使得在python3中發送和接受郵件變得更簡單。你不需要手動添加服務器地址、端口以及適合的協議,zmail會幫你完成。此外,使用一個python字典來代表郵件內容也更符合直覺
安裝
Zmail僅支持python3,不需要任何外部依賴. 不支持python2.
1
|
pip3 install zmail |
特性
- 自動尋找服務器地址以及端口
- 自動使用可靠的鏈接協議
- 自動將一個python字典映射成MIME對象(帶有附件的)
- 自動添加頭文件以及localhostname來避免服務器拒收你的郵件
- 輕松自定義你的頭文件
- 支持使用HTML作為郵件內容
- 僅需python>=3.5,你可以將其嵌入你的項目而無需其他的依賴
使用須知
使用它之前,請保證
- 使用Python3
- 確保打開了郵箱的POP3和SMTP功能 (對于 @163.com 和 @gmail.com 你需要設置你的應用專用密碼)
然后,剩下你需要做的就是import zmail即可
使用示例
發送你的郵件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import zmail # 你的郵件內容 mail_content = { "subject" : "success!" , # 郵件主題 "content_text" : "This message from zmail" , # 郵件內容 "attachments" :r "D:\test.docx" , # 郵件附件 } # 使用你的郵件賬戶名和密碼登錄服務器 # 發送郵件 |
給多個信箱發件,修改發送郵件 即可,其他內容同上
1
2
3
|
發送HTML作為郵件內容
1
2
3
4
5
6
|
mail = { 'subject' : 'Success!' , # 郵件主題 'content_html' : [ 'HTML CONTENT' ], # HTML格式的郵件內容 'attachments' : '/Users/zyh/Documents/example.zip' , # 郵件附件 } |
或者
1
2
3
4
5
6
7
8
|
with open ( '/Users/example.html' , 'r' ) as f: content_html = f.read() mail = { 'subject' : 'Success!' , 'content_html' : content_html, 'attachments' : '/Users/zyh/Documents/example.zip' , } |
- 自定義你的server
如果zmail不能正常工作,你可以自定義server的配置
1
|
server = zmail.server( 'username' , 'password' ,smtp_host = 'smtp.163.com' ,smtp_port = 994 ,smtp_ssl = True ,pop_host = 'pop.163.com' ,pop_port = 995 ,pop_tls = True ) |
取回你的郵件
- 取得最新的郵件
1
2
3
|
- 依據id取回郵件
1
|
mail = server.get_mail( 2 ) |
- 依據 (subject,after,before,sender)取回一個列表的郵件
1
|
mail = server.get_mails(subject = '163' ,after = '2018-1-1' ,sender = 'github' ) |
示例中, 如果 '163' 在郵件的主題中,這封郵件將會被匹配, 例如' [163] Your password has changed'
郵件的結構
- content-type: 郵件內容的類型
- subject: 郵件主題
- to:收件人
- from:寄件人
- date: 年-月-日 時間 時區
- boundary: 如果郵件為multiple - - - parts,你可以得到其分界線
- content: 郵件的文本內容(僅在text/plain時可以被解析)
- contents: 郵件的body,里面包含著由分界線分割的每一個段落
- attachments: None 或者 [['附件名稱;編碼方式','附件的二進制內容']...]
- id: 在郵箱中的id
項目地址:
GitHub:https://github.com/ZYunH/zmail
以上就是python Zmail模塊簡介與使用示例的詳細內容,更多關于python Zmail模塊的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/zhouyxh/p/12320708.html