Django+jenkins+python(1) 轉寄郵件

來源:互聯網
上載者:User

標籤:style   oba   擷取   文本   init   ext   else   gets   etc   

在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())) )

Django+jenkins+python(1) 轉寄郵件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.