本文主要教大家如何簡單實作python收發郵件功能,知識要點在python內建的poplib和stmplib模組的使用上。具有一定的參考價值,有興趣的夥伴可以參考一下,希望能幫助大家。
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'
# 登录邮箱 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')
('+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 None
def retr(self, which): """Retrieve whole message number 'which'. Result is in form ['response', ['line', ...], octets]. """ return self._longcmd('RETR %s' % which)
3. smtp發送郵件
和pop一樣,使用smtp之前也要先給它一些需要的常數:self.mail_box = smtplib.SMTP(self.smtpHost, self.port) self.mail_box.login(self.userName, self.passWord)
# 发送邮件 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)
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)
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.
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()
以上是python收發郵件功能的簡單實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!