• python 收发邮件


    今天记录一下怎样使用python收发邮件,知识要点在python内置的poplib和stmplib模块的使用上。

    1. 准备工作

    首先,我们须要有一个測试邮箱。我们使用新浪邮箱,并且要进行例如以下设置:

    在新浪邮箱首页的右上角找到设置->很多其它设置,然后在左边选择“client/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。smtpserver及port。我们调用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()

    在登录邮箱的时候,非常自然,我们须要提供username和password,如上述代码所看到的,使用非常easy。

    登录邮箱成功后,我们能够使用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 None
    poplib获取邮件内容的接口是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发送邮件的代码!非常easy有木有。非常方便有木有!非常通俗易懂有木有!

    这里主要就是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邮箱。

    測试结果例如以下:

    好的,大家能够把上面的代码复制一下,自己玩一下呗~~~

  • 相关阅读:
    《例说51单片机(C语言版)(第3版)》——1-3 认识MCS-51的存储器结构
    MySQL5.7中InnoDB不可不知的新特性
    python 抓取日志
    Packet for query is too large (1706 > 1024). You can change this value on the server by setting the
    面对1.3 亿用户数据泄露,企业如何围绕核心数据构建安全管理体系?
    python 正则替换
    python 正则
    没有宫廷内斗,数据库界的延禧攻略
    抽象基类
    ansible -m shell -a 注意单引号和双引号
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7204454.html
Copyright © 2020-2023  润新知