python發送各類郵件的主要方法

 python中email模塊使得處理郵件變得比較簡單,今天着重學習了一下發送郵件的具體做法,這裏寫寫自己的的心得,也請高手給些指點。

    一、相關模塊介紹

    發送郵件主要用到了smtplib和email兩個模塊,這裏首先就兩個模塊進行一下簡單的介紹:
    1、smtplib模塊

      smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])

   SMTP類構造函數,表示與SMTP服務器之間的連接,通過這個連接可以向smtp服務器發送指令,執行相關操作(如:登陸、發送郵件)。所有參數都是可選的。

     host:smtp服務器主機名

     port:smtp服務的端口,默認是25;如果在創建SMTP對象的時候提供了這兩個參數,在初始化的時候會自動調用connect方法去連接服務器。

   smtplib模塊還提供了SMTP_SSL類和LMTP類,對它們的操作與SMTP基本一致。

  smtplib.SMTP提供的方法:

     SMTP.set_debuglevel(level):設置是否爲調試模式。默認爲False,即非調試模式,表示不輸出任何調試信息。

     SMTP.connect([host[, port]]):連接到指定的smtp服務器。參數分別表示smpt主機和端口。注意: 也可以在host參數中指定端口號(如:smpt.yeah.net:25),這樣就沒必要給出port參數。

     SMTP.docmd(cmd[, argstring]):向smtp服務器發送指令。可選參數argstring表示指令的參數。

     SMTP.helo([hostname]) :使用"helo"指令向服務器確認身份。相當於告訴smtp服務器“我是誰”。

     SMTP.has_extn(name):判斷指定名稱在服務器郵件列表中是否存在。出於安全考慮,smtp服務器往往屏蔽了該指令。

     SMTP.verify(address) :判斷指定郵件地址是否在服務器中存在。出於安全考慮,smtp服務器往往屏蔽了該指令。

     SMTP.login(user, password) :登陸到smtp服務器。現在幾乎所有的smtp服務器,都必須在驗證用戶信息合法之後才允許發送郵件。

     SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]) :發送郵件。這裏要注意一下第三個參數,msg是字符串,表示郵件。我們知道郵件一般由標題,發信人,收件人,郵件內容,附件等構成,發送郵件的時候,要注意msg的格式。這個格式就是smtp協議中定義的格式。

     SMTP.quit() :斷開與smtp服務器的連接,相當於發送"quit"指令。(很多程序中都用到了smtp.close(),具體與quit的區別google了一下,也沒找到答案。)

     2、email模塊

     emial模塊用來處理郵件消息,包括MIME和其他基於RFC 2822 的消息文檔。使用這些模塊來定義郵件的內容,是非常簡單的。其包括的類有(更加詳細的介紹可見:http://docs.python.org/library/email.mime.html):

    class email.mime.base.MIMEBase(_maintype, _subtype, **_params):這是MIME的一個基類。一般不需要在使用時創建實例。其中_maintype是內容類型,如text或者image。_subtype是內容的minor type 類型,如plain或者gif。 **_params是一個字典,直接傳遞給Message.add_header()。

    class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]:MIMEBase的一個子類,多個MIME對象的集合,_subtype默認值爲mixed。boundary是MIMEMultipart的邊界,默認邊界是可數的。

    class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]):MIMEMultipart的一個子類。

    class email.mime.audio. MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME音頻對象

    class email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):MIME二進制文件對象。

    class email.mime.message.MIMEMessage(_msg[, _subtype]):具體的一個message實例,使用方法如下:

   

msg=mail.Message.Message()    #一個實例 
msg['to']='[email protected]' #發送到哪裏
msg['from']='[email protected]' #自己的郵件地址
msg['date']='2012-3-16' #時間日期
msg['subject']='hello world' #郵件主題

 

    class email.mime.text.MIMEText(_text[, _subtype[, _charset]]):MIME文本對象,其中_text是郵件內容,_subtype郵件類型,可以是text/plain(普通文本郵件),html/plain(html郵件),  _charset編碼,可以是gb2312等等。

    二、幾種郵件的具體實現代碼

    1、普通文本郵件

    普通文本郵件發送的實現,關鍵是要將MIMEText中_subtype設置爲plain。首先導入smtplib和mimetext。創建smtplib.smtp實例,connect郵件smtp服務器,login後發送,具體代碼如下:(python2.6下實現)

複製代碼
# -*- coding: UTF-8 -*-
'''
發送txt文本郵件
小五義:http://www.cnblogs.com/xiaowuyi
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=[[email protected]]
mail_host="smtp.XXX.com" #設置服務器
mail_user="XXXX" #用戶名
mail_pass="XXXXXX" #口令
mail_postfix="XXX.com" #發件箱的後綴

def send_mail(to_list,sub,content):
me="hello"+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_subtype='plain',_charset='gb2312')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","hello world!"):
print "發送成功"
else:
print "發送失敗"
複製代碼

    2、html郵件的發送

    與text郵件不同之處就是將將MIMEText中_subtype設置爲html。具體代碼如下:(python2.6下實現)

複製代碼
# -*- coding: utf-8 -*-
'''
發送html文本郵件
小五義:http://www.cnblogs.com/xiaowuyi
'''
import smtplib
from email.mime.text import MIMEText
mailto_list=["[email protected]"]
mail_host="smtp.XXX.com" #設置服務器
mail_user="XXX" #用戶名
mail_pass="XXXX" #口令
mail_postfix="XXX.com" #發件箱的後綴

def send_mail(to_list,sub,content): #to_list:收件人;sub:主題;content:郵件內容
me="hello"+"<"+mail_user+"@"+mail_postfix+">" #這裏的hello可以任意設置,收到信後,將按照設置顯示
msg = MIMEText(content,_subtype='html',_charset='gb2312') #創建一個實例,這裏設置爲html格式郵件
msg['Subject'] = sub #設置主題
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host) #連接smtp服務器
s.login(mail_user,mail_pass) #登陸服務器
s.sendmail(me, to_list, msg.as_string()) #發送郵件
s.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五義</a>"):
print "發送成功"
else:
print "發送失敗"

複製代碼

   3、發送帶附件的郵件

    發送帶附件的郵件,首先要創建MIMEMultipart()實例,然後構造附件,如果有多個附件,可依次構造,最後利用smtplib.smtp發送。

複製代碼
# -*- coding: cp936 -*-
'''
發送帶附件郵件
小五義:http://www.cnblogs.com/xiaowuyi
'''

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

#創建一個帶附件的實例
msg = MIMEMultipart()

#構造附件1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.doc"'#這裏的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
msg.attach(att1)

#構造附件2
att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)

#加郵件頭
msg['to'] = '[email protected]'
msg['from'] = '[email protected]'
msg['subject'] = 'hello world'
#發送郵件
try:
server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXX')#XXX爲用戶名,XXXXX爲密碼
server.sendmail(msg['from'], msg['to'],msg.as_string())
server.quit()
print '發送成功'
except Exception, e:
print str(e)
複製代碼

     4、利用MIMEimage發送圖片

   

複製代碼
# -*- coding: cp936 -*-
import smtplib
import mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def AutoSendMail():
msg = MIMEMultipart()
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = "hello world"


txt = MIMEText("這是中文的郵件內容哦",'plain','gb2312')
msg.attach(txt)


file1 = "C:\\hello.jpg"
image = MIMEImage(open(file1,'rb').read())
image.add_header('Content-ID','<image1>')
msg.attach(image)


server = smtplib.SMTP()
server.connect('smtp.XXX.com')
server.login('XXX','XXXXXX')
server.sendmail(msg['From'],msg['To'],msg.as_string())
server.quit()

if __name__ == "__main__":
AutoSendMail()
複製代碼

   

    利用MIMEimage發送圖片,原本是想圖片能夠在正文中顯示,可是代碼運行後發現,依然是以附件形式發送的,希望有高手能夠指點一下,如何可以發送在正文中顯示的圖片的郵件,就是圖片是附件中存在,但同時能顯示在正文中,具體形式如下圖。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章