小編給大家分享一下如何實現python收發郵件功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

1. 準備工作
首先,我們需要有一個測試郵箱,我們使用新浪郵箱,而且要進行如下設置:

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

最后,將Pop3/smtp服務的服務狀態打開即可:

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服務器及端口。我們調用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方法有一個默認參數which,其默認值為None,當調用者沒有給出參數時,該方法會列出所有郵件的信息,其返回形式為 [response, ['msg_number, octets', ...], octets],其中,response為響應結果,msg_number是郵件編號,octets為8位字節單位。我們看一看具體例子:
('+OK ', ['1 2424', '2 2422'], 16)
這是一個調用list()方法以后的返回結果。很明顯,這是一個tuple,第一個值sahib響應結果'+OK',表示請求成功,第二個值為一個數組,存儲了郵件的信息。例如'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 Nonepoplib獲取郵件內容的接口是retr方法。其需要一個參數,該參數為要獲取的郵件編號。下面是retr方法的定義:
def retr(self, which):
"""Retrieve whole message number 'which'.
Result is in form ['response', ['line', ...], octets].
"""
return self._longcmd('RETR %s' % which)我們看到注釋,可以知道,retr方法可以獲取指定編號的郵件的全部內容,其返回形式為[response, ['line', ...], octets],可見,郵件的內容是存儲在返回的tuple的第二個元素中,其存儲形式為一個數組。我們測試一下,該數組是怎么樣的。

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

嗯...大家可以自己試一下。
3. smtp發送郵件
和pop一樣,使用smtp之前也要先給它提供一些需要的常量:
self.mail_box = smtplib.SMTP(self.smtpHost, self.port) self.mail_box.login(self.userName, self.passWord)
上面是使用smtp登錄郵箱的代碼,和pop類似。下面給出使用smtp發送郵件的代碼,你會看到python是多么的簡單優美!
# 發送郵件 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發送郵件的代碼!很簡單有木有!很方便有木有!很通俗易懂有木有!這里主要就是sendmail這個方法,指定發送方,接收方和郵件內容就可以了。還有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)看注釋~~~ 這就是一個生成指定內容,指定編碼的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發送郵件的內容大概就這樣了。
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()
# 發送郵件
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()上述代碼先登錄郵箱,然后獲取其第一封郵件并刪除之,然后獲取該郵件的主題和發送方并打印出來,最后再發送一封成功郵件給另一個bossMail郵箱。
測試結果如下:

看完了這篇文章,相信你對“如何實現python收發郵件功能”有了一定的了解,如果想了解更多相關知識,歡迎關注創新互聯成都網站設計公司行業資訊頻道,感謝各位的閱讀!
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網站名稱:如何實現python收發郵件功能-創新互聯
URL標題:http://www.yijiale78.com/article18/pipgp.html
成都網站建設公司_創新互聯,為您提供靜態網站、手機網站建設、定制開發、外貿網站建設、自適應網站、網站導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯