本文主要教大家如何簡單實作python收發郵件功能,知識要點在python內建的poplib和stmplib模組的使用上。具有一定的參考價值,有興趣的夥伴可以參考一下,希望能幫助大家。
1. 準備工作
首先,我們需要有一個測試郵箱,我們使用新浪郵箱,而且要進行如下設定:
#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的第二個元素中,其儲存形式為一個陣列。我們測試一下,該數組是怎麼樣的。
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收發郵件功能的簡單實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...

如何使用正則表達式匹配到第一個閉合標籤就停止?在處理HTML或其他標記語言時,常常需要使用正則表達式來�...

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載
最受歡迎的的開源編輯器

WebStorm Mac版
好用的JavaScript開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。