下面簡單介紹下如何使用python發送郵件,包括普通常值內容,也可以帶附件,或者HTML內容的郵件。可以說有了python,一切都變得非常的容易。
smtplib 模組是用來發送email的標準module,另外配合email.mime內的幾個module實現起來就非常的簡單。
[python]
view plaincopyprint?
- def sendmail(message):
- try:
- smtp = smtplib.SMTP(EMAIL_HOST)
- smtp.login(EMAIL_USER, EMAIL_PWD)
- smtp.sendmail(EMAIL_USER+"@"+EMAIL_POSTFIX, TO_EMAIL, message)
- smtp.quit()
- print 'email send success.'
- except Exception ,e:
- print e
- print 'email send failed.'
def sendmail(message): try: smtp = smtplib.SMTP(EMAIL_HOST) smtp.login(EMAIL_USER, EMAIL_PWD) smtp.sendmail(EMAIL_USER+"@"+EMAIL_POSTFIX, TO_EMAIL, message) smtp.quit() print 'email send success.' except Exception ,e: print e print 'email send failed.'
首先要匯入smtplib模組,加入import smtplib,初始化的時候直接連上郵箱伺服器,也就是上面的EMAIL_HOST(我使用的是163郵箱,所以定義EMAIL_HOST = 'smtp.163.com'),由於目前的郵箱基本都需要登入才可以使用,所以要調用smtp.login()函數,輸入使用者和密碼。
[python]
view plaincopyprint?
- def sendwithoutattachment():
- msg = MIMEText(getcontent(), 'plain','utf-8')
- getheader(msg)
-
- sendmail(msg.as_string())
def sendwithoutattachment(): msg = MIMEText(getcontent(), 'plain','utf-8') getheader(msg) sendmail(msg.as_string())
我將發送簡單常值內容的郵件單獨獨立為一個函數,使用MIMEText產生,注意這裡用到了utf-8,因為內容有可能是中文,所以要特別指定。如果要發送html內容,則講plain更改為html即可。
[python]
view plaincopyprint?
- def getheader(msg):
- msg['From'] = ME
- msg['To'] = ";".join(TO_EMAIL)
- msg['Subject'] = EMAIL_HEADER
- msg['Date'] = formatdate(localtime=True)
def getheader(msg): msg['From'] = ME msg['To'] = ";".join(TO_EMAIL) msg['Subject'] = EMAIL_HEADER msg['Date'] = formatdate(localtime=True)
getheader函數是用來設定寄件者,接受者,主題和發送時間的。
[python]
view plaincopyprint?
- def getcontent():
- path = os.getcwd()
- file = os.path.join(path, CONTENT_FILE_NAME)
- content = open(file, 'rb')
- data = content.read()
- try:
- data = data.decode('gbk')
- except :
- data = data.decode('gbk','ignore')
- content.close()
- return data
def getcontent(): path = os.getcwd() file = os.path.join(path, CONTENT_FILE_NAME) content = open(file, 'rb') data = content.read() try: data = data.decode('gbk') except : data = data.decode('gbk','ignore') content.close() return data
至於郵件內文,我是事先寫到一個TXT文檔中,讀取出來。這樣也比較隱蔽。:)要主意中文編碼。
[python]
view plaincopyprint?
- def getattachment(msg):
- ctype, encoding = mimetypes.guess_type(ACCESSORY_FULLPATH)
- if ctype is None or encoding is not None:
- ctype = 'application/octet-stream'
- maintype, subtype = ctype.split('/', 1)
-
- #Formating accessory data
- data = open(ACCESSORY_FULLPATH, 'rb')
- file_msg = MIMEBase(maintype, subtype)
- file_msg.set_payload(data.read( ))
- data.close( )
- encode_base64(file_msg)
- #file_msg["Content-Type"] = ctype # if add type then return error 10054
- file_msg.add_header('Content-Disposition', 'attachment', filename = ACCESSORY_NAME)
- msg.attach(file_msg)
def getattachment(msg): ctype, encoding = mimetypes.guess_type(ACCESSORY_FULLPATH) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) #Formating accessory data data = open(ACCESSORY_FULLPATH, 'rb') file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read( )) data.close( ) encode_base64(file_msg) #file_msg["Content-Type"] = ctype # if add type then return error 10054 file_msg.add_header('Content-Disposition', 'attachment', filename = ACCESSORY_NAME) msg.attach(file_msg)
附件同樣獨立為一個函數來建立,這裡要注意的是不要指定“Content-Type”類型,否則無法發送郵件。這個問題還沒有解決。
以上基本包括了發送郵件的主要幾個函數,具體smtplib模組和MIME等內容,資料很多,這裡就不詳細講解了,有感興趣的可以上網search。