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('\r\n'.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())) )