簡(jiǎn)單實(shí)現(xiàn)python收發(fā)郵件功能
今天記錄一下如何使用python收發(fā)郵件,知識(shí)要點(diǎn)在python內(nèi)置的poplib和stmplib模塊的使用上。
1. 準(zhǔn)備工作
首先,我們需要有一個(gè)測(cè)試郵箱,我們使用新浪郵箱,而且要進(jì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()
在登錄郵箱的時(shí)候,很自然,我們需要提供用戶名和密碼,如上述代碼所示,使用非常簡(jiǎn)單。
登錄郵箱成功后,我們可以使用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方法有一個(gè)默認(rèn)參數(shù)which,其默認(rèn)值為None,當(dāng)調(diào)用者沒有給出參數(shù)時(shí),該方法會(huì)列出所有郵件的信息,其返回形式為 [response, ['msg_number, octets', ...], octets],其中,response為響應(yīng)結(jié)果,msg_number是郵件編號(hào),octets為8位字節(jié)單位。我們看一看具體例子:
('+OK ', ['1 2424', '2 2422'], 16)
這是一個(gè)調(diào)用list()方法以后的返回結(jié)果。很明顯,這是一個(gè)tuple,第一個(gè)值sahib響應(yīng)結(jié)果'+OK',表示請(qǐng)求成功,第二個(gè)值為一個(gè)數(shù)組,存儲(chǔ)了郵件的信息。例如'1 2424'中的1表示該郵件編號(hào)為1。
下面我們?cè)倏慈绾问褂胮oplib下載郵件。
# 獲取郵件 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方法。其需要一個(gè)參數(shù),該參數(shù)為要獲取的郵件編號(hào)。下面是retr方法的定義:
def retr(self, which): """Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets]. """ return self._longcmd('RETR %s' % which)
我們看到注釋,可以知道,retr方法可以獲取指定編號(hào)的郵件的全部?jī)?nèi)容,其返回形式為[response, ['line', ...], octets],可見,郵件的內(nèi)容是存儲(chǔ)在返回的tuple的第二個(gè)元素中,其存儲(chǔ)形式為一個(gè)數(shù)組。我們測(cè)試一下,該數(shù)組是怎么樣的。
我們可以看到,這個(gè)數(shù)組的存儲(chǔ)形式類似于一個(gè)dict!于是,我們可以據(jù)此找到任何我們感興趣的內(nèi)容。例如,我們的示例代碼是要找到郵件的主題以及發(fā)送者,就可以按照上面的代碼那樣編寫。當(dāng)然,你也可以使用正則匹配~~~ 下面是測(cè)試結(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ā)送郵件的代碼,你會(huì)看到python是多么的簡(jiǎn)單優(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ā)送郵件的代碼!很簡(jiǎn)單有木有!很方便有木有!很通俗易懂有木有!這里主要就是sendmail這個(gè)方法,指定發(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)
看注釋~~~ 這就是一個(gè)生成指定內(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. 源碼及測(cè)試
# -*- 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ā)送一封成功郵件給另一個(gè)bossMail郵箱。
測(cè)試結(jié)果如下:
好的,大家可以把上面的代碼復(fù)制一下,自己玩一下唄
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python登錄pop3郵件服務(wù)器接收郵件的方法
- python發(fā)送郵件接收郵件示例分享
- Python實(shí)現(xiàn)發(fā)送與接收郵件的方法詳解
- 利用python發(fā)送和接收郵件
- Python接收Gmail新郵件并發(fā)送到gtalk的方法
- 在Python中使用poplib模塊收取郵件的教程
- 在Python的Flask框架下收發(fā)電子郵件的教程
- Python使用smtp和pop簡(jiǎn)單收發(fā)郵件完整實(shí)例
- python smtplib模塊自動(dòng)收發(fā)郵件功能(一)
- python smtplib模塊自動(dòng)收發(fā)郵件功能(二)
- Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼
- python實(shí)現(xiàn)的接收郵件功能示例【基于網(wǎng)易POP3服務(wù)器】
相關(guān)文章
Python自動(dòng)化辦公之Word轉(zhuǎn)PDF的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹一下如何在?windows、mac、linux?三種系統(tǒng)中都可以生成?PDF?的解決方案,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-05-05Python設(shè)計(jì)模式之工廠方法模式實(shí)例詳解
這篇文章主要介紹了Python設(shè)計(jì)模式之工廠方法模式,結(jié)合實(shí)例形式較為詳細(xì)的分析了工廠方法模式的概念、原理、用法及相關(guān)操作技巧,需要的朋友可以參考下2019-01-01Python-jenkins模塊之folder相關(guān)操作介紹
這篇文章主要介紹了Python-jenkins模塊之folder相關(guān)操作介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05簡(jiǎn)單理解Python中基于生成器的狀態(tài)機(jī)
這篇文章主要介紹了簡(jiǎn)單理解Python中基于生成器的狀態(tài)機(jī),來自于IBM官方技術(shù)文檔,需要的朋友可以參考下2015-04-04基于進(jìn)程內(nèi)通訊的python聊天室實(shí)現(xiàn)方法
這篇文章主要介紹了基于進(jìn)程內(nèi)通訊的python聊天室實(shí)現(xiàn)方法,實(shí)例分析了Python聊天室的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-06-06python3 unicode列表轉(zhuǎn)換為中文的實(shí)例
今天小編就為大家分享一篇python3 unicode列表轉(zhuǎn)換為中文的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10Python內(nèi)置函數(shù)memoryview()的實(shí)現(xiàn)示例
本文主要介紹了Python內(nèi)置函數(shù)memoryview()的實(shí)現(xiàn)示例,它允許你在不復(fù)制其內(nèi)容的情況下操作同一個(gè)數(shù)組的不同切片,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05