• Django+jenkins+python(1) 转发邮件


    在Jenkins获取邮件

    fetch_email.py

    #coding=utf-8
    import poplib
    from email.parser import Parser
    from email.header import decode_header




    def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
    content_type = msg.get('Content-Type','').lower()
    pos = content_type.find('charset=')
    if pos >=0:
    charset = content_type[pos + 8:].strip()
    return charset

    def decode_str(s):
    value,charset = decode_header(s)[0]
    if charset:
    value = value.decode(charset)
    return value

    class FetchMail():

    def __init__(self,server,user,passwd):
    self.server = server
    self.user = user
    self.passwd = passwd

    def getLatestEmailContent(self):
    initialServer = poplib.POP3(self.server)
    initialServer.user(self.user)
    initialServer.pass_(self.passwd)
    resp, mails, octets = initialServer.list()
    resp, lines, octets = initialServer.retr(len(mails))
    msg = Parser().parsestr(' '.join(lines))
    return msg
    def getAddress(self,msg):
    value = msg.get('To', '')
    if value:
    value = decode_str(value)
    return value
    else:
    raise Exception('Cannot found the email address',value)
    def getSubject(self,msg):
    value = msg.get('Subject', '')
    if value:
    value = decode_str(value)
    return value
    else:
    raise Exception('Cannot got the subject', value)
    def getDetailsContent(self,msg):
    global content
    if (msg.is_multipart()):
    # 如果邮件对象是一个MIMEMultipart,
    # get_payload()返回list,包含所有的子对象:
    parts = msg.get_payload()
    for n, part in enumerate(parts):
    # print('%spart %s' % (' ' * indent, n))
    # print('%s||||||||||||||||||||||||' % (' ' * indent))
    # 递归打印每一个子对象:
    self.getDetailsContent(part)
    else:
    # 邮件对象不是一个MIMEMultipart,
    # 就根据content_type判断:
    content_type = msg.get_content_type()
    if content_type == 'text/plain' or content_type == 'text/html':
    # 纯文本或HTML内容:
    content = msg.get_payload(decode=True)
    # 要检测文本编码:
    charset = guess_charset(msg)
    if charset:
    content = content.decode(charset)

    # print('%sText: %s' % (' ' * indent, content + '...'))
    # print "content"+content
    else:
    # 不是文本,作为附件处理:
    print('%sAttachment: %s' % (' ', content_type))
    return 'Fail'

    return content

    if __name__ == '__main__':
    server = FetchMail('xx','xx','xx')
    print server.getLatestEmailContent()
    print ('Suject: %s Address:%s'% (server.getSubject(server.getLatestEmailContent()),server.getAddress(server.getLatestEmailContent())) )

  • 相关阅读:
    【年度回顾】2020,云开发的20个重大更新
    SQL 排序检索数据
    【JVM进阶之路】三:探究虚拟机对象
    【JVM进阶之路】二:Java内存区域
    【JVM进阶之路】一:Java虚拟机概览
    这些不可不知的JVM知识,我都用思维导图整理好了
    计算机网络的七层结构、五层结构和四层结构
    synchronized详解
    Linux内核中I2C总线及设备长啥样?
    C语言中这些预定义宏的不可不会
  • 原文地址:https://www.cnblogs.com/QAZLIU/p/5748180.html
Copyright © 2020-2023  润新知