天天看點

python子產品學習 ---- smtplib 郵件發送

在基于網際網路的應用中,程式經常需要自動地發送電子郵件。如:一個網站的注冊系統會在使用者注冊時發送一封郵件來确認注冊;當使用者忘記登陸密碼的時 候,通過郵件來取回密碼。smtplib子產品是python中smtp(簡單郵件傳輸協定)的用戶端實作。我們可以使用smtplib子產品,輕松的發送電 子郵件。下面的例子用了不到十行代碼來發送電子郵件:

  1. #coding=gbk   
  2. import  smtplib   
  3. smtp = smtplib.SMTP()   
  4. smtp.connect("smtp.yeah.net" ,  "25" )   
  5. smtp.login('使用者名' ,  '密碼' )   
  6. smtp.sendmail('[email protected]' ,  '[email protected]' ,  'From: [email protected]/r/nTo: [email protected]/r/nSubject: this is a email from python demo/r/n/r/nJust for test~_~' )   
  7. smtp.quit()  

#coding=gbk

import smtplib

smtp = smtplib.SMTP()

smtp.connect("smtp.yeah.net", "25")

smtp.login('使用者名', '密碼')

smtp.sendmail('[email protected]', '[email protected]', 'From:

[email protected]/r/nTo: [email protected]/r/nSubject: this is a email from python

demo/r/n/r/nJust for test~_~')

smtp.quit()

  這個例子夠簡單吧^_^!下面詳細介紹stmplib子產品中的類和方法。

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

  SMTP類構造函數,表示與SMTP伺服器之間的連接配接,通過這個連接配接我們可以向smtp伺服器發送指令,執行相關操作(如:登陸、發送郵件)。 該類提供了許多方法,将在下面介紹。它的所有參數都是可選的,其中host參數表示smtp伺服器主機名,上面例子中的smtp主機 為"smtp.yeah.net";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表示指令的參數。下面的例子完全通過調用docmd方法向伺服器發送指令來實作郵件的發 送(在smtp.yeah.net郵件伺服器上試驗通過。其他郵件伺服器沒有試過):

  1. import  smtplib, base64, time  
  2. userName = base64.encodestring('from' ).strip()  
  3. password = base64.encodestring('password' ).strip()  
  4. smtp = smtplib.SMTP()  
  5. smtp.connect("smtp.yeah.net:25" )  
  6. print  smtp.docmd( 'helo' ,  'from' )  
  7. print  smtp.docmd( 'auth login' )  
  8. print  smtp.docmd(userName)  
  9. print  smtp.docmd(password)  
  10. print  smtp.docmd( 'mail from:' ,  '<[email protected]>' )  
  11. print  smtp.docmd( 'rcpt to:' ,  '<[email protected]>' )  
  12. #data 指令表示郵件内容   
  13. print  smtp.docmd( 'data' )  
  14. print  smtp.docmd( '' '''from: [email protected]  
  15. to: [email protected]  
  16. subject: subject  
  17. email body  
  18. .  
  19. ''' )  
  20. smtp.quit()  

import smtplib, base64, time

userName = base64.encodestring('from').strip()

password = base64.encodestring('password').strip()

smtp = smtplib.SMTP()

smtp.connect("smtp.yeah.net:25")

print smtp.docmd('helo', 'from')

print smtp.docmd('auth login')

print smtp.docmd(userName)

print smtp.docmd(password)

print smtp.docmd('mail from:', '<[email protected]>')

print smtp.docmd('rcpt to:', '<[email protected]>')

#data 指令表示郵件内容

print smtp.docmd('data')

print smtp.docmd('''from: [email protected]

to: [email protected]

subject: subject

email body

.

''')

smtp.quit()

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協定中定義的格式。在上面的例子中,msg的值為:

  1. '' '''From: [email protected]  
  2. To: [email protected]  
  3. Subject: test  
  4. just for test'''   

'''From: [email protected]

To: [email protected]

Subject: test

just for test'''

  這個字元串的的意思表示郵件發件人為"[email protected]",收件人為" [email protected]",郵件标題為"test",郵件内容為"just for test"。細心的你可能會疑問:如果要發送的郵件内容很複雜,包含圖檔、視訊、附件等内容,按照MIME的格式來拼接字元串,将是一件非常麻煩的事。不 用擔心,python已經考慮到了這點,它為我們提供了email子產品,使用該子產品可以輕松的發送帶圖檔、視訊、附件等複雜内容的郵件。在介紹完 smtplib子產品之後,我會簡單介紹email子產品的基本使用。

SMTP.quit()

  斷開與smtp伺服器的連接配接,相當于發送"quit"指令。

email及其相關子子產品

  emial子產品用來處理郵件消息,包括MIME和其他基于RFC 2822 的消息文檔。使 用這些子產品來定義郵件的内容,是非常簡單的。下面是一些常用的類:

class email.mime.multipart. MIMEMultipart: 多個MIME對象的集合。

class email.mime.audio. MIMEAudio: MIME音頻對象。

class email.mime.image. MIMEImage: MIME二進制檔案對象。

class email.mime.text. MIMEText: MIME文本對象。

  看上面的解釋可能會覺得雲裡霧裡,其實我對smtp, MIME的了解也很膚淺。但在大多數時候,我們隻要會用就可以了。下面是一個簡單的例子來示範如何使用這些類來發送帶附件的郵件:

  1. #coding=gbk   
  2. import  smtplib, mimetypes  
  3. from  email.mime.text  import  MIMEText  
  4. from  email.mime.multipart  import  MIMEMultipart  
  5. from  email.mime.image  import  MIMEImage  
  6. msg = MIMEMultipart()  
  7. msg['From' ] =  "[email protected]"   
  8. msg['To' ] =  '[email protected]'   
  9. msg['Subject' ] =  'email for tesing'   
  10. # 添加郵件内容   
  11. txt = MIMEText("這是郵件内容~~" )  
  12. msg.attach(txt)  
  13. #添加二進制附件   
  14. fileName = r'e:/PyQt4.rar'   
  15. ctype, encoding = mimetypes.guess_type(fileName)  
  16. if  ctype  is   None   or  encoding  is   not   None :  
  17.     ctype = 'application/octet-stream'   
  18. maintype, subtype = ctype.split('/' ,  1 )  
  19. att1 = MIMEImage((lambda  f: (f.read(), f.close()))(open(fileName,  'rb' ))[ 0 ], _subtype = subtype)  
  20. att1.add_header('Content-Disposition' ,  'attachment' , filename = fileName)  
  21. msg.attach(att1)  
  22. #發送郵件   
  23. smtp = smtplib.SMTP()  
  24. smtp.connect('smtp.yeah.net:25' )  
  25. smtp.login('from' ,  '密碼' )  
  26. smtp.sendmail('[email protected]' ,  '[email protected]' , msg.as_string())  
  27. smtp.quit()  
  28. print   '郵件發送成功'   

#coding=gbk

import smtplib, mimetypes

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

from email.mime.image import MIMEImage

msg = MIMEMultipart()

msg['From'] = "[email protected]"

msg['To'] = '[email protected]'

msg['Subject'] = 'email for tesing'

#添加郵件内容

txt = MIMEText("這是郵件内容~~")

msg.attach(txt)

#添加二進制附件

fileName = r'e:/PyQt4.rar'

ctype, encoding = mimetypes.guess_type(fileName)

if ctype is None or encoding is not None:

ctype = 'application/octet-stream'

maintype, subtype = ctype.split('/', 1)

att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName,

'rb'))[0], _subtype = subtype)

att1.add_header('Content-Disposition', 'attachment', filename =

fileName)

msg.attach(att1)

#發送郵件

smtp = smtplib.SMTP()

smtp.connect('smtp.yeah.net:25')

smtp.login('from', '密碼')

smtp.sendmail('[email protected]', '[email protected]', msg.as_string())

smtp.quit()

print '郵件發送成功'

  是不是很簡單。簡單就是美,用最少的代碼把問題解決,這就是Python。更多關于smtplib的資訊,請參考Python手冊 smtplib 子產品。