用腳本語言發送郵件是系統管理員必備技能
對系統定期檢查或者當服務器受到***時生成文檔和報表。
發佈這些文檔最快速有效的方法就是發送郵件。
python中email模塊使得處理郵件變得比較簡單
發送郵件主要用到了smtplib和email兩個模塊,這裏首先就兩個模塊進行一下簡單的介紹:
本段摘錄於 http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html
1、smtplib模塊
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP類構造函數,表示與SMTP服務器之間的連接,通過這個連接可以向smtp服務器發送指令,執行相關操作(如:登陸、發送郵件)。所有參數都是可選的。
host:smtp服務器主機名 例:stmp.qq.com 或 stmp.163.com
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實例,使用方法如下:
[python] view plain copy
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後發送,具體代碼如下:(python3下實現)
import smtplib import string from email.header import Header from email.mime.text import MIMEText HOST='smtp.qq.com' #定義郵箱類型 SUBJECT = '***報警' #定義郵件標題 TO = '[email protected]' #定義接受郵箱 FROM ='[email protected]' #定義發送郵箱 msg = MIMEText("hello","plain","utf-8") #郵件內容 msg['Subject'] = SUBJECT #郵件標題 msg['From']=FROM #發送郵件 msg['To']=TO #接受郵箱 try: s=smtplib.SMTP_SSL(HOST,465) #以SSL協議連接到qq郵箱 s.login("[email protected]","dzvgafguqkqfffhg") #登錄qq郵箱 參數1:發送郵箱 參數2:郵箱密碼 s.sendmail(FROM,TO,msg.as_string()) #發送郵件 s.quit() #退出登錄 print('郵件發送陳功') except Exception as e: print('失敗',e)
2、html郵件的發送
與text郵件不同之處就是將將MIMEText中_subtype設置爲html。具體代碼如下:(python2.6下實現)
import smtplib import string from email.header import Header from email.mime.text import MIMEText HOST='smtp.qq.com' #定義發送郵箱類型 SUBJECT = '***報警' #定義郵件標題 TO = '[email protected]' #定義接受郵件 FROM ='[email protected]' #定義發送郵件 msg = MIMEText(""" <html> <head> <tiltle>最簡單的網頁</tiltle> <head> <body> <body bgcolor="#000000"> <center> <h2> <font style="color:#DC143C">郵件測試</font> </h2> <p> <font style="color:#DC143C">如果你發現這個網頁證明我正在測試</font> </P> <img src="http://a.cphotos.bdimg.com/timg?image&quality=100&size=b4000_4000&sec=1503817907&di=fd44277924745914f28fe32e7c21d48c&src=http://img.zcool.cn/community/016d1f555c85a80000009c5049f63e.jpg"> <h2> <font style="color:#DC143C">如有打擾!敬請原諒</font> </h2> </center> </body> </html> ""","html","utf-8") #參數1:內容 參數二:類型 參數三:編碼 msg['Subject'] = SUBJECT #郵件標題 msg['From']=FROM #發送郵箱 msg['To']=TO #接受郵箱 try: s=smtplib.SMTP_SSL(HOST,465) #同上一個的代碼 s.login("[email protected]","dzvgafguqkqfffhg") #同上一個的代碼 s.sendmail(FROM,TO,msg.as_string()) s.quit() print('郵件發送陳功') except Exception as e: print('失敗',e)
3、發送帶附件的郵件
發送帶附件的郵件,首先要創建MIMEMultipart()實例,然後構造附件,如果有多個附件,可依次構造,最後利用
import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # 郵件發送 HOST = 'smtp.qq.com' SUBJECT = '圖表' TO = '[email protected]' FROM = '[email protected]' def adding(src,imgid): fp = open(src,'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID',imgid) return msgImage msg=MIMEMultipart('related') msgtext = MIMEText(""" <html> <head> <title>as</title> </head> <body> <font color = blue>相見時>難別亦難</font> <br/> <img src='cid:ok'><br/> </body> </html>","html","utf8") #參數1:內容 參數二:類型 參數三:編碼 msg.attach(msgtext) #給msgtext中添加附件 msg.attach(adding("1.png","ok")) #給html中添加本地圖片 files = MIMEApplication(open('100.xlsx','rb').read()) #添加附件100.xlsx files.add_header('Content-Disposition', 'attachment', filename="100.xlsx") #設置附件的頭 msg.attach(files) #加入附加files(files就是100xlsx) msg['Subject'] = SUBJECT msg['FROM'] = FROM msg['TO'] = TO try: s = smtplib.SMTP_SSL(HOST,465) s.login('[email protected]','lvbjkgwkzgquffhe') s.sendmail(FROM,TO,msg.as_string()) s.quit() print('郵件發送成功') except Exception as e: print('失敗'+str(e))
更多郵件發送類型請參照 http://www.jb51.net/article/49216.htm
小白筆記 如有錯誤 請提醒修改