1. 程式人生 > >python 構建和解析郵件

python 構建和解析郵件

用python寫傳統的郵件

from email.mime.text import MIMEText
message = ''' hello jason
it is a test mail
please accept it'''

msg = MIMEText(message)
msg['To'] = '[email protected]'
msg['From'] = 'jason <[email protected]>'
msg['Subject'] = 'test mail'

print msg.as_string()

結果:
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
To: 
[email protected]
From: jason <[email protected]> Subject: test mail hello jason it is a test mail please accept it

預設添加了3個頭部Content-Type,MIME-Version,Content-Transfer-Encoding,而且也已經排好了版,這樣的郵件,如果理解發送是可以的。如果想延遲傳送的話,最好還是要加上Date和Message-ID頭部,可以通過下面的方式來新增。
from email.mime.text import MIMEText
from email import Utils
message = ''' hello jason
it is a test mail
please accept it'''

msg = MIMEText(message)
msg['To'] = '
[email protected]
' msg['From'] = 'jason <[email protected]>' msg['Subject'] = 'test mail' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() print msg.as_string()

結果:

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
To: 
[email protected]
From: jason <[email protected]> Subject: test mail Date: Wed, 27 Mar 2013 11:48:59 +0800 Message-ID: <[email protected]> hello jason it is a test mail please accept it

這樣的郵件就可以正確的被髮送了

解析郵件

import sys,email

msg = email.message_from_file(sys.stdin)
print "*** Headers in message: "
for header,value in msg.items():
    print header+":"
    print " "+value
if msg.is_multipart():
    print "mail is MIME type, can't resolve it."
    sys.exit(1)
else:
    print "-" * 78
    if 'subject' in msg:
        print "Subject: ",msg['subject']
        print "-" * 78
    print "Message body:"
    print
    print msg.get_payload()

把郵件顯示結果寫入到一個mail.txt檔案中。

from email.mime.text import MIMEText
from email import Utils

message = ''' hello jason
it is a test mail
please accept it'''

msg = MIMEText(message)
msg['To'] = '[email protected]'
msg['From'] = 'jason <[email protected]>'
msg['Subject'] = 'test mail'
msg['Date'] = Utils.formatdate(localtime=1)
msg['Message-ID'] = Utils.make_msgid()  
fd = open('mail.txt','w')
fd.write(msg.as_string()) 
fd.close()


通過這個把剛剛顯示出來的郵件,以一種更可讀的方式顯示出來,如下圖:

構造MIME郵件

上面說的都是些純文字郵件,那麼如何才能讓郵件傳送非純文字郵件呢,這個就設計到了MIME,大家可以跟著到google查一下。

提幾個重點步驟吧!

1. 建立一個MIMEMultipart()物件,設定郵件的header。

2.為郵件部分內容建立一個MIMEText()物件,把它放到MIMEMultipart()物件中。

3.為每一個附件,建立一個合適的MIME物件,也把他放到MIMEMultipart()物件中。

4.呼叫MIMEMultipart()物件中的as_string()函式來得到作為結果的郵件。

下面我們就用python來構造MIME格式的郵件,這個是可以新增附件的郵件格式。

email_mime.py

from email import Utils,Encoders
import mimetypes,sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase

def attachment(filename):
    fd = open(filename,'rb')
    mimetype,mimeencoding = mimetypes.guess_type(filename)
    if mimetype or (mimeencoding is None):
        mimetype = 'application/octet-stream'
    maintype,subtype = mimetype.split('/')
    if maintype == 'text':
        retval = MIMEText(fd.read(),_subtype=subtype)
    else:
        retval = MIMEBase(maintype,subtype)
        retval.set_payload(fd.read())
        Encoders.encode_base64(retval)
    retval.add_header('Content-Disposition','attachment',filename = filename)
    fd.close()
    return retval

message = ''' hello jason
it is a test mail
please accept it'''

msg = MIMEMultipart()
msg['To'] = '[email protected]'
msg['From'] = 'jason <[email protected]>'
msg['Subject'] = 'test mail'
msg['Date'] = Utils.formatdate(localtime=1)
msg['Message-ID'] = Utils.make_msgid()

body = MIMEText(message)
msg.attach(body)
for filename in sys.argv[1:]:
    msg.attach(attachment(filename))
print msg.as_string()

執行指令碼(這裡添加了mail.txt和Loadrunner.rar作為附件):

python email_mime.py mail.txt Loadrunner.rar > results.txt
Content-Type: multipart/mixed; boundary="===============1228986135=="
MIME-Version: 1.0
To: [email protected]
From: jason <[email protected]>
Subject: test mail
Date: Wed, 27 Mar 2013 14:31:02 +0800
Message-ID: <[email protected]>

--===============1228986135==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

 hello jason
it is a test mail
please accept it
--===============1228986135==
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="mail.txt"

Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSINCk1JTUUtVmVyc2lv
bjogMS4wDQpDb250ZW50LVRyYW5zZmVyLUVuY29kaW5nOiA3Yml0DQpUbzogeHh4eHhAcXEuY29t
DQpGcm9tOiBqYXNvbiA8bWp6aGVuZ0B4eHh4eC5jb20+DQpTdWJqZWN0OiB0ZXN0IG1haWwNCkRh
dGU6IFdlZCwgMjcgTWFyIDIwMTMgMTI6NTU6MTMgKzA4MDANCk1lc3NhZ2UtSUQ6IDwyMDEzMDMy
NzA0NTUxMy4xMzc1Mi4xNTU1NkBaR0MtMjAxMjEyMTlaS0o+DQoNCiBoZWxsbyBqYXNvbg0KaXQg
aXMgYSB0ZXN0IG1haWwNCnBsZWFzZSBhY2NlcHQgaXQ=
--===============1228986135==
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Loadrunner.rar"

UmFyIRoHAM+QcwAADQAAAAAAAAADJXRAgiwAa0EBAADwAwACkyympH2W+TAdMwwAIAAAAGxtNzAu
ZGxsAAHABhgl1VUMiNXgGmIzJMkmAYExbBsVistY2naRtlsg0LA7YVMAVMTI4OYRSBFoFxyi0UzG
lUgwcmNmHDGnWjaPaFpbR7Ttp37TvaFuWojBDpIVlCVSpGkaxtlt5LmVYqdGNYGfn3esnqzMmtb3
zmeiQG1759/X+NpM5zfN+rWtb1vW9a1vXOfxLX/CefP98+b1vet89MzOYeeL+j/7TGYAFAACay42
...

構造成功。

注意這裡的Content-Type(內容型別)和Content-Transfer-Encoding(內容傳輸編碼格式)的變化

但是呢,有個問題就是為什麼mail.txt檔案為什麼識別不了呢,應該識別成功text/plian的內容格式啊。

查了一下,發現mimetypes模組是通過呼叫mimetypes.pyc檔案的,檢視一下mimetypes.py檔案

可以看到

knownfiles = [
    "/etc/mime.types",
    "/etc/httpd/mime.types",                    # Mac OS X
    "/etc/httpd/conf/mime.types",               # Apache
    "/etc/apache/mime.types",                   # Apache 1
    "/etc/apache2/mime.types",                  # Apache 2
    "/usr/local/etc/httpd/conf/mime.types",
    "/usr/local/lib/netscape/mime.types",
    "/usr/local/etc/httpd/conf/mime.types",     # Apache 1.2
    "/usr/local/etc/mime.types",                # Apache 1.3
    ]

因為我是在windows環境下執行的,所以當然找不到所識別的mime型別啦

相關推薦

python 構建解析郵件

用python寫傳統的郵件 from email.mime.text import MIMEText message = ''' hello jason it is a test mail please accept it''' msg = MIMEText(messa

【Java TCP/IP Socket程式設計】----傳送接收資料----構建解析協議訊息

--------筆記來自於書籍《Java TCP/IP Socket程式設計》。 簡介 使用套接字時,通常要麼是需要同時建立通訊通道兩端的程式,要麼實現一個給定的協議進行通訊。如果知道通訊雙方都使用java實現,且擁有對協議的完全控制權,那麼就可以使用Java的內建工具如Serialiabl

java學習——json的構建解析

1、什麼是json JSON(JavaScript Object Notation)是一種與開發語言無關的,輕量級的資料格式。json是由key和value組成: { "title" : "JSON入門-Java篇", "author" : "Anthony", "author" :

極簡機器學習課程:使用Python構建訓練一個完整的人工神經網

直接閱讀技術類的教材是困難的,理論的密集程度常常令人生畏,而Welch Labs的視訊用有趣的短片形式,以達到教學的目的,並結合相關資源介紹技術背景,使你能熟練掌握主題。 而本文介紹的系列,將帶領大家使用Python構建和訓練一個完整的人工神經網路。1.資料+架構 要想使用一種機器學習的方

Python載入解析包含多個JSON物件的JSON檔案

近期工作中,有一個爬蟲任務直接將文字內容存為了.json檔案,之後領導又給了個解析json檔案裡部分內容的需求,開始直接用with open開啟檔案用json.load讀取,然而因為一個檔案裡存在多個json物件,所以,失敗。網上相關操作資料貌似也並不多,在這裡

python傳送、解析郵件

參考資料 http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=575710 總體來說python處理郵件還是比較方便的,庫提供了很多工具.下面我把心得寫出來,給新手一個啟迪,也請高手給些更好的方法.  先說接

Python:minidom模塊(DOM寫入解析XML)

ice 美化 odin xml文件 高級 獲取 node 錯誤信息 tel 一、DOM寫XML文件 #導入minidom from xml.dom import minidom # 1.創建DOM樹對象 dom=minidom.Document() # 2.創建根節點。每

利用Python imaplibemail模塊 讀取郵件文本內容及附件內容

multi 首部 nco mes art out ear .py gb2312 #! encoding:utf8 ‘‘‘ 環境: Win10 64位 Python 2.7.5 參考: http://www.pythonclub.org/python-ne

構建分離解析的域名服務器,以及實現SNATDNAT 轉換

ret for bsp all 網關 span onf tor refresh 分離解析(Split DNS)的域名服務器實際也是主域名服務器,這裏主要是指根據不同的客戶端提供不同的域名解析記錄。來自不同地址的客戶機請求解析同一域名時,為其提供不同的解析結果。 實驗準

使用flex進行網易雲音樂界面構建布局解析

tel ace fixed size 易雲 spl .com -h recommend 1.為什麽要用flex進行webapp布局 第一,float布局 需要清除浮動,很麻煩。 第二,絕對定位需要考慮位置和空間占位 第三,元素垂直水平居中問題。 2.網易雲音樂首頁分析3.啥

用flex進行網易雲音樂界面構建布局解析(2)

基礎知識 query 項目 了解 ado 輪播圖 wid 又是 外星人 前面我們通過《css布局簡史與決勝未來的第四代css布局技術》了解了css布局發展史和未來,下面,我們通過《使用flex進行網易雲音樂界面構建和布局解析》了解一下,如何在實際項目中使用flex進行布局,

使用 Redis Python 構建一個共享單車的應用程式

  學習如何使用 Redis 和 Python 構建一個位置感知的應用程式。 我經常出差。但不是一個汽車狂熱分子,所以當我有空閒時,我更喜歡在城市中散步或者騎單車。我參觀過的許多城市都有共享單車系統,你可以租個單車用幾個小時。 大多數系統都有一個應用程式來幫助使用者定位和

氣象資料Grib格式解析Python程式碼Matlab程式碼

       以.grb/.grb1/.grb2為副檔名的都是氣象資料,氣象資料中可以儲存多個內容,如雲量、雪深、氣壓、風速等內容,或者具有時間序列的雲量等。這些檔案不可以直接開啟成圖片,若想直觀地檢視grib資料,需要讀取檔案並將其解析出

Python虛擬環境的構建使用

---恢復內容開始--- 虛擬環境構建和使用

python學習手冊(第4版) 第二十章 迭代解析

列表解析: >>> ord('a')                                      # ord將單個字元轉為ASCII整數編碼 97 >>> chr(97)                         

Python基於tkinter傳送接收郵件

一、效果演示 二、傳送郵件程式碼 import smtplib import tkinter class Window: def __init__(self,root): label1 = tkinter.Label(root,text='SMTP

Python 語言學習 第六篇:迭代解析

Python 語言學習 第六篇:迭代和解析 Python中的迭代是指按照元素的順序逐個呼叫的過程,迭代概念包括:迭代協議、可迭代物件和迭代器三個概念。 迭代協議是指有__next__()函式的物件會前進到下一個結果,而到達系列的末尾時,則會引發StopIteration異常。為了支援迭代協議

Python UnboundLocalErrorNameError錯誤根源解析

如果程式碼風格相對而言不是那麼的pythonic,或許很少碰到這類錯誤。當然並不是不鼓勵使用一些python語言的技巧。如果遇到這這種型別的錯誤,說明我們對python中變數引用相關部分有不當的認識和理解。而這又是對理解python相關概念比較重要的。這也是本文寫作的原因。  本文為理解閉包相關概念的做鋪墊,

以太坊原始碼解讀(9)以太坊的P2P模組解析——底層網路構建啟動

以太坊的底層p2pServer,大約可以分為三層: 1、底層:table物件、node物件,它們分別定義了底層的路由表以及本地節點的資料結構、搜尋和驗證;     1)database.go         //封裝node資料庫相關操作     2)node.go 

python中的日誌操作傳送郵件

1、python中的日誌操作 安裝log模組:pip install nnlog  引數:my_log = nnlog.Logger('server_log.log',level='debug',backCount=5,when='D',interval=2) ‘serv