用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: <20130327034859.14284.670@ZGC-20121219ZKJ>
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: <20130327063102.12588.91954@ZGC-20121219ZKJ>
--===============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類型啦