python 發郵件腳本
相關模塊介紹
發送郵件主要用到了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‘ #郵件主題
簡單的使用
import smtplib from email.mime.text import MIMEText mail_host="xxx.xxx.com" #設置服務器 mail_user="[email protected]" #用戶名 mail_pass="xxxxxx" #密碼 mail_postfix="xxxx.com" #發件箱的後綴 def send_mail(to_list,sub,content): me = ‘%s<%[email protected]%s>‘ % (sub, ‘xxxx‘, mail_postfix) msg = MIMEText(content,_subtype=‘plain‘,_charset=‘UTF-8‘) 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__‘: emails=[‘[email protected]‘] #目標郵箱 if send_mail(emails,"郵件測試","郵件測試!郵件測試!"): print "發送成功" else: print "發送失敗"
python 發郵件腳本