簡單實現(xiàn)python收發(fā)郵件功能
今天記錄一下如何使用python收發(fā)郵件,知識要點在python內(nèi)置的poplib和stmplib模塊的使用上。
1. 準備工作
首先,我們需要有一個測試郵箱,我們使用新浪郵箱,而且要進行如下設置:

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

最后,將Pop3/smtp服務的服務狀態(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服務器及端口。我們調(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方法有一個默認參數(shù)which,其默認值為None,當調(diào)用者沒有給出參數(shù)時,該方法會列出所有郵件的信息,其返回形式為 [response, ['msg_number, octets', ...], octets],其中,response為響應結果,msg_number是郵件編號,octets為8位字節(jié)單位。我們看一看具體例子:
('+OK ', ['1 2424', '2 2422'], 16)
這是一個調(diào)用list()方法以后的返回結果。很明顯,這是一個tuple,第一個值sahib響應結果'+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ā)送者,就可以按照上面的代碼那樣編寫。當然,你也可以使用正則匹配~~~ 下面是測試結果:

嗯...大家可以自己試一下。
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郵箱。
測試結果如下:

好的,大家可以把上面的代碼復制一下,自己玩一下唄
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- python登錄pop3郵件服務器接收郵件的方法
- python發(fā)送郵件接收郵件示例分享
- Python實現(xiàn)發(fā)送與接收郵件的方法詳解
- 利用python發(fā)送和接收郵件
- Python接收Gmail新郵件并發(fā)送到gtalk的方法
- 在Python中使用poplib模塊收取郵件的教程
- 在Python的Flask框架下收發(fā)電子郵件的教程
- Python使用smtp和pop簡單收發(fā)郵件完整實例
- python smtplib模塊自動收發(fā)郵件功能(一)
- python smtplib模塊自動收發(fā)郵件功能(二)
- Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼
- python實現(xiàn)的接收郵件功能示例【基于網(wǎng)易POP3服務器】
相關文章
基于進程內(nèi)通訊的python聊天室實現(xiàn)方法
這篇文章主要介紹了基于進程內(nèi)通訊的python聊天室實現(xiàn)方法,實例分析了Python聊天室的相關實現(xiàn)技巧,需要的朋友可以參考下2015-06-06
Python內(nèi)置函數(shù)memoryview()的實現(xiàn)示例
本文主要介紹了Python內(nèi)置函數(shù)memoryview()的實現(xiàn)示例,它允許你在不復制其內(nèi)容的情況下操作同一個數(shù)組的不同切片,具有一定的參考價值,感興趣的可以了解一下2024-05-05

