Get mail at Jenkins
fetch_email.py
#coding =utf-8
Import Poplib
From Email.parserImport Parser
From Email.headerImport Decode_header
def guess_charset (msg):
CharSet = Msg.get_charset ()
If CharSetIsNone:
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
RaiseException (' cannot found the email address ', value]
Def getsubject (SELF,MSG):
Value = Msg.get (' Subject ',‘‘)
If value:
Value = Decode_str (value)
return value
Else
RaiseException (' cannot got the subject ', value)
Def getdetailscontent (SELF,MSG):
Global content
if (Msg.is_multipart ()):
# If the Mail object is a Mimemultipart,
# Get_payload () returns a list that contains all the child objects:
Parts = Msg.get_payload ()
For N, partInchEnumerate (Parts):
# print ('%spart%s '% (' * indent, N))
# print ('%s| | | | | | | | | | | | | | | | |--("* indent)"
# recursively print each sub-object:
Self.getdetailscontent (part)
Else
# The Mail object is not a mimemultipart,
# as judged by Content_Type:
Content_Type = Msg.get_content_type ()
if Content_Type = =' Text/plain 'or Content_Type = =' Text/html ':
# Plain text or HTML content:
Content = Msg.get_payload (Decode=True)
# to detect text encoding:
CharSet = Guess_charset (msg)
If CharSet:
Content = Content.decode (charset)
# print ('%stext:%s '% (' * indent, content + ' ... '))
# print "Content" +content
Else
# is not text and is handled as an attachment:
Print'%sattachment:%s '% (", Content_Type))
Return
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 ())))
Django+jenkins+python (1) Forward mail