zoukankan      html  css  js  c++  java
  • 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())) )

  • 相关阅读:
    怎么查看当前进程?怎么执行退出?怎么查看当前路径?
    简述正则表达式及其用途?
    Java 中,抽象类与接口之间有什么不同?
    哪个命令专门用来查看后台任务?
    什么是线程池?有哪几种创建方式?
    什么是多线程的上下文切换?
    WebApplicationContext?
    synchronized、volatile、CAS 比较?
    使用 Spring 有哪些方式?
    线程池的优点?
  • 原文地址:https://www.cnblogs.com/QAZLIU/p/5748180.html
Copyright © 2011-2022 走看看