欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

簡單實現(xiàn)python收發(fā)郵件功能

 更新時間:2018年01月05日 13:52:15   作者:GuityCrown  
這篇文章主要教大家如何簡單實現(xiàn)python收發(fā)郵件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

今天記錄一下如何使用python收發(fā)郵件,知識要點在python內(nèi)置的poplib和stmplib模塊的使用上。

1. 準(zhǔn)備工作

首先,我們需要有一個測試郵箱,我們使用新浪郵箱,而且要進行如下設(shè)置:

在新浪郵箱首頁的右上角找到設(shè)置->更多設(shè)置,然后在左邊選擇“客戶端/pop/imap/smtp”:

最后,將Pop3/smtp服務(wù)的服務(wù)狀態(tài)打開即可:

2. poplib接收郵件

首先,介紹一下poplib登錄郵箱和下載郵件的一些接口:

self.popHost = 'pop.sina.com' 
self.smtpHost = 'smtp.sina.com' 
self.port = 25 
self.userName = 'xxxxxx@sina.com' 
self.passWord = 'xxxxxx' 
self.bossMail = 'xxxxxx@qq.com' 

我們需要如上一些常量,用于指定登錄郵箱以及pop,smtp服務(wù)器及端口。我們調(diào)用poplib的POP3_SSL接口可以登錄到郵箱。

# 登錄郵箱 
def login(self): 
 try: 
  self.mailLink = poplib.POP3_SSL(self.popHost) 
  self.mailLink.set_debuglevel(0) 
  self.mailLink.user(self.userName) 
  self.mailLink.pass_(self.passWord) 
  self.mailLink.list() 
  print u'login success!' 
 except Exception as e: 
  print u'login fail! ' + str(e) 
  quit() 

在登錄郵箱的時候,很自然,我們需要提供用戶名和密碼,如上述代碼所示,使用非常簡單。
登錄郵箱成功后,我們可以使用list方法獲取郵箱的郵件信息。我們看到list方法的定義:

def list(self, which=None): 
 """Request listing, return result. 
 
 Result without a message number argument is in form 
 ['response', ['mesg_num octets', ...], octets]. 
 
 Result when a message number argument is given is a 
 single response: the "scan listing" for that message. 
 """ 
 if which is not None: 
  return self._shortcmd('LIST %s' % which) 
 return self._longcmd('LIST') 

我們看到list方法的注釋,其中文意思是,list方法有一個默認(rèn)參數(shù)which,其默認(rèn)值為None,當(dāng)調(diào)用者沒有給出參數(shù)時,該方法會列出所有郵件的信息,其返回形式為 [response, ['msg_number, octets', ...], octets],其中,response為響應(yīng)結(jié)果,msg_number是郵件編號,octets為8位字節(jié)單位。我們看一看具體例子:
('+OK ', ['1 2424', '2 2422'], 16)
這是一個調(diào)用list()方法以后的返回結(jié)果。很明顯,這是一個tuple,第一個值sahib響應(yīng)結(jié)果'+OK',表示請求成功,第二個值為一個數(shù)組,存儲了郵件的信息。例如'1 2424'中的1表示該郵件編號為1。
下面我們再看如何使用poplib下載郵件。

# 獲取郵件 
def retrMail(self): 
 try: 
  mail_list = self.mailLink.list()[1] 
  if len(mail_list) == 0: 
   return None 
  mail_info = mail_list[0].split(' ') 
  number = mail_info[0] 
  mail = self.mailLink.retr(number)[1] 
  self.mailLink.dele(number) 
 
  subject = u'' 
  sender = u'' 
  for i in range(0, len(mail)): 
   if mail[i].startswith('Subject'): 
    subject = mail[i][9:] 
   if mail[i].startswith('X-Sender'): 
    sender = mail[i][10:] 
  content = {'subject': subject, 'sender': sender} 
  return content 
 except Exception as e: 
  print str(e) 
  return None 

poplib獲取郵件內(nèi)容的接口是retr方法。其需要一個參數(shù),該參數(shù)為要獲取的郵件編號。下面是retr方法的定義:

def retr(self, which): 
 """Retrieve whole message number 'which'. 
 
 Result is in form ['response', ['line', ...], octets]. 
 """ 
 return self._longcmd('RETR %s' % which) 

我們看到注釋,可以知道,retr方法可以獲取指定編號的郵件的全部內(nèi)容,其返回形式為[response, ['line', ...], octets],可見,郵件的內(nèi)容是存儲在返回的tuple的第二個元素中,其存儲形式為一個數(shù)組。我們測試一下,該數(shù)組是怎么樣的。

我們可以看到,這個數(shù)組的存儲形式類似于一個dict!于是,我們可以據(jù)此找到任何我們感興趣的內(nèi)容。例如,我們的示例代碼是要找到郵件的主題以及發(fā)送者,就可以按照上面的代碼那樣編寫。當(dāng)然,你也可以使用正則匹配~~~ 下面是測試結(jié)果:

嗯...大家可以自己試一下。

3. smtp發(fā)送郵件

和pop一樣,使用smtp之前也要先給它提供一些需要的常量:

self.mail_box = smtplib.SMTP(self.smtpHost, self.port) 
self.mail_box.login(self.userName, self.passWord) 

上面是使用smtp登錄郵箱的代碼,和pop類似。下面給出使用smtp發(fā)送郵件的代碼,你會看到python是多么的簡單優(yōu)美!

# 發(fā)送郵件 
def sendMsg(self, mail_body='Success!'): 
 try: 
  msg = MIMEText(mail_body, 'plain', 'utf-8') 
  msg['Subject'] = mail_body 
  msg['from'] = self.userName 
  self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) 
  print u'send mail success!' 
 except Exception as e: 
  print u'send mail fail! ' + str(e) 

這就是python用smtp發(fā)送郵件的代碼!很簡單有木有!很方便有木有!很通俗易懂有木有!這里主要就是sendmail這個方法,指定發(fā)送方,接收方和郵件內(nèi)容就可以了。還有MIMEText可以看它的定義如下:

class MIMEText(MIMENonMultipart): 
 """Class for generating text/* type MIME documents.""" 
 
 def __init__(self, _text, _subtype='plain', _charset='us-ascii'): 
  """Create a text/* type MIME document. 
 
  _text is the string for this message object. 
 
  _subtype is the MIME sub content type, defaulting to "plain". 
 
  _charset is the character set parameter added to the Content-Type 
  header. This defaults to "us-ascii". Note that as a side-effect, the 
  Content-Transfer-Encoding header will also be set. 
  """ 
  MIMENonMultipart.__init__(self, 'text', _subtype, 
         **{'charset': _charset}) 
  self.set_payload(_text, _charset) 

看注釋~~~ 這就是一個生成指定內(nèi)容,指定編碼的MIME文檔的方法而已。順便看看sendmail方法吧~~~

def sendmail(self, from_addr, to_addrs, msg, mail_options=[], 
    rcpt_options=[]): 
 """This command performs an entire mail transaction. 
 
 The arguments are: 
  - from_addr : The address sending this mail. 
  - to_addrs  : A list of addresses to send this mail to. A bare 
       string will be treated as a list with 1 address. 
  - msg   : The message to send. 
  - mail_options : List of ESMTP options (such as 8bitmime) for the 
       mail command. 
  - rcpt_options : List of ESMTP options (such as DSN commands) for 
       all the rcpt commands. 

嗯...使用smtp發(fā)送郵件的內(nèi)容大概就這樣了。

4. 源碼及測試

# -*- coding:utf-8 -*- 
from email.mime.text import MIMEText 
import poplib 
import smtplib 
 
 
class MailManager(object): 
 
 def __init__(self): 
  self.popHost = 'pop.sina.com' 
  self.smtpHost = 'smtp.sina.com' 
  self.port = 25 
  self.userName = 'xxxxxx@sina.com' 
  self.passWord = 'xxxxxx' 
  self.bossMail = 'xxxxxx@qq.com' 
  self.login() 
  self.configMailBox() 
 
 # 登錄郵箱 
 def login(self): 
  try: 
   self.mailLink = poplib.POP3_SSL(self.popHost) 
   self.mailLink.set_debuglevel(0) 
   self.mailLink.user(self.userName) 
   self.mailLink.pass_(self.passWord) 
   self.mailLink.list() 
   print u'login success!' 
  except Exception as e: 
   print u'login fail! ' + str(e) 
   quit() 
 
 # 獲取郵件 
 def retrMail(self): 
  try: 
   mail_list = self.mailLink.list()[1] 
   if len(mail_list) == 0: 
    return None 
   mail_info = mail_list[0].split(' ') 
   number = mail_info[0] 
   mail = self.mailLink.retr(number)[1] 
   self.mailLink.dele(number) 
 
   subject = u'' 
   sender = u'' 
   for i in range(0, len(mail)): 
    if mail[i].startswith('Subject'): 
     subject = mail[i][9:] 
    if mail[i].startswith('X-Sender'): 
     sender = mail[i][10:] 
   content = {'subject': subject, 'sender': sender} 
   return content 
  except Exception as e: 
   print str(e) 
   return None 
 
 def configMailBox(self): 
  try: 
   self.mail_box = smtplib.SMTP(self.smtpHost, self.port) 
   self.mail_box.login(self.userName, self.passWord) 
   print u'config mailbox success!' 
  except Exception as e: 
   print u'config mailbox fail! ' + str(e) 
   quit() 
 
 # 發(fā)送郵件 
 def sendMsg(self, mail_body='Success!'): 
  try: 
   msg = MIMEText(mail_body, 'plain', 'utf-8') 
   msg['Subject'] = mail_body 
   msg['from'] = self.userName 
   self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) 
   print u'send mail success!' 
  except Exception as e: 
   print u'send mail fail! ' + str(e) 
 
if __name__ == '__main__': 
 mailManager = MailManager() 
 mail = mailManager.retrMail() 
 if mail != None: 
  print mail 
  mailManager.sendMsg() 

上述代碼先登錄郵箱,然后獲取其第一封郵件并刪除之,然后獲取該郵件的主題和發(fā)送方并打印出來,最后再發(fā)送一封成功郵件給另一個bossMail郵箱。

測試結(jié)果如下:

好的,大家可以把上面的代碼復(fù)制一下,自己玩一下唄

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python自動化辦公之Word轉(zhuǎn)PDF的實現(xiàn)

    Python自動化辦公之Word轉(zhuǎn)PDF的實現(xiàn)

    這篇文章主要為大家詳細(xì)介紹一下如何在?windows、mac、linux?三種系統(tǒng)中都可以生成?PDF?的解決方案,文中的示例代碼講解詳細(xì),需要的可以參考一下
    2022-05-05
  • Python設(shè)計模式之工廠方法模式實例詳解

    Python設(shè)計模式之工廠方法模式實例詳解

    這篇文章主要介紹了Python設(shè)計模式之工廠方法模式,結(jié)合實例形式較為詳細(xì)的分析了工廠方法模式的概念、原理、用法及相關(guān)操作技巧,需要的朋友可以參考下
    2019-01-01
  • Python 中 list 的各項操作技巧

    Python 中 list 的各項操作技巧

    最近在學(xué)習(xí) python 語言。大致學(xué)習(xí)了 python 的基礎(chǔ)語法。覺得 python 在數(shù)據(jù)處理中的地位和它的 list 操作密不可分,今天把相關(guān)基礎(chǔ)操作記錄到腳本之家平臺,需要的的朋友參考下
    2017-04-04
  • Python-jenkins模塊之folder相關(guān)操作介紹

    Python-jenkins模塊之folder相關(guān)操作介紹

    這篇文章主要介紹了Python-jenkins模塊之folder相關(guān)操作介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • 簡單理解Python中基于生成器的狀態(tài)機

    簡單理解Python中基于生成器的狀態(tài)機

    這篇文章主要介紹了簡單理解Python中基于生成器的狀態(tài)機,來自于IBM官方技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • 基于進程內(nèi)通訊的python聊天室實現(xiàn)方法

    基于進程內(nèi)通訊的python聊天室實現(xiàn)方法

    這篇文章主要介紹了基于進程內(nèi)通訊的python聊天室實現(xiàn)方法,實例分析了Python聊天室的相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2015-06-06
  • python3 unicode列表轉(zhuǎn)換為中文的實例

    python3 unicode列表轉(zhuǎn)換為中文的實例

    今天小編就為大家分享一篇python3 unicode列表轉(zhuǎn)換為中文的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • 兒童python練習(xí)實例

    兒童python練習(xí)實例

    小編在網(wǎng)上整理了關(guān)于兒童python相關(guān)編程的練習(xí)實例,如果有小朋友對此感興趣可以學(xué)習(xí)下。
    2018-05-05
  • Python內(nèi)置函數(shù)memoryview()的實現(xiàn)示例

    Python內(nèi)置函數(shù)memoryview()的實現(xiàn)示例

    本文主要介紹了Python內(nèi)置函數(shù)memoryview()的實現(xiàn)示例,它允許你在不復(fù)制其內(nèi)容的情況下操作同一個數(shù)組的不同切片,具有一定的參考價值,感興趣的可以了解一下
    2024-05-05
  • Python中字典的setdefault()方法教程

    Python中字典的setdefault()方法教程

    在學(xué)習(xí)python字典操作方法時,感覺setdefault()方法,比字典的其它基本操作方法更難理解的同學(xué)比較多,所以想著總結(jié)以下,下面這篇文章主要給大家介紹了Python中字典的setdefault()方法,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-02-02

最新評論