溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python中怎么提取郵件內(nèi)容

發(fā)布時(shí)間:2021-07-02 16:04:53 來(lái)源:億速云 閱讀:371 作者:Leah 欄目:大數(shù)據(jù)

這篇文章將為大家詳細(xì)講解有關(guān)Python中怎么提取郵件內(nèi)容,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

基礎(chǔ)信息準(zhǔn)備

import imaplib, email,re,requests,time,pymysqlimapserver = 'smtp.office365.com'emailuser = "qa.notice@shangri-la.com"emailpasswd = "test123"
#beta環(huán)境禪道地址beta_loginhost="http://zen.beta.com/index.php?m=user&f=login"beta_add_bughost="http://zen.beta.com/index.php?m=bug&f=create&productID=10&branch=0&extra=moduleID=0"
#live環(huán)境禪道地址live_loginhost="https://zen.live.com/index.php?m=user&f=login"live_add_bughost="https://zen.live.com/index.php?m=bug&f=create&productID=10&branch=0&extra=moduleID=0"
envs="live" #定義使用的環(huán)境

   

數(shù)據(jù)庫(kù)連接信息

#連接數(shù)據(jù)庫(kù)相關(guān)的信息:beta_dicts={ "HOST" : '10.8.2.3', "PORT" : 3306, "USER": 'zentao', "PASSWORD" : 'test123', "NAME":"zentao"}live_dicts={ "HOST" : '10.7.1.7', "PORT" : 3306, "USER": 'zentao', "PASSWORD" : 'test123', "NAME":"zentao"}

   

數(shù)據(jù)庫(kù)查詢


#數(shù)據(jù)庫(kù)查詢操作def executesql(query,envs): try: if(envs=="beta"): conn = pymysql.connect(beta_dicts['HOST'], beta_dicts['USER'], beta_dicts['PASSWORD'], beta_dicts['NAME'], int(beta_dicts['PORT']),charset='utf8') print(beta_dicts) else: conn = pymysql.connect(live_dicts['HOST'], live_dicts['USER'], live_dicts['PASSWORD'], live_dicts['NAME'], int(live_dicts['PORT']),charset='utf8') print(live_dicts) cursor = conn.cursor() cursor.execute(query) result =cursor.fetchall() print("execute successfully!!!") if(len(result)==0): return 0 else: return result[0][0] except Exception as e: print(e) print("execute failed") finally: cursor.close() conn.close()

   

建立連接與檢索

#建立連接與檢索匹配的郵件def search(): print("start to connect") conn = imaplib.IMAP4_SSL(imapserver) conn.login(emailuser, emailpasswd) conn.select('INBOX') # 選擇收件箱(默認(rèn)) print(conn) now = time.localtime() nowt = time.strftime("%d-%b-%Y", now) print(nowt) results , data = conn.search(None,'(FROM "Liang.Wu")','(ON "'+str(nowt)+'")') mailidlist = data[0].split() print(mailidlist) try: for id in mailidlist: print(id) resultss, data = conn.fetch(id, '(RFC822)') # 通過(guò)郵件id獲取郵件,data是fetch到的郵件具體內(nèi)容 e = email.message_from_bytes(data[0][1])

   

解釋說(shuō)明與print

 ''' Header()類: email.header.Header(s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict') 其中參數(shù)的含義理解如下: s:標(biāo)頭的值,也就是對(duì)應(yīng) From、To、Subject 的值;  charset:字符集格式,默認(rèn)是 ASCII,但是一般指定 UTF-8 格式以兼容更多字符;  header_name:標(biāo)頭名,就是 From、To、Subject、Time 等; ''' subject = email.header.make_header(email.header.decode_header(e['SUBJECT'])) mail_from = email.header.make_header(email.header.decode_header(e['From'])) print("郵件的subject是%s" % subject) print("郵件的發(fā)件人是%s" % mail_from) body = str(get_body(e), encoding='ISO-8859-1') # utf-8 gb2312 GB18030解析中文日文英文 print("郵件內(nèi)容是%s" % body) parse1(body) print("good job") except Exception as e: print("we catch an error!!!",e) finally: print("logout is success") print("the finally of operation!!!") conn.logout()

   

獲取郵件主體信息

#獲取郵件主體信息def get_body(msg): if msg.is_multipart ():#Return True if the message’s payload is a list of sub-Message objects, otherwise return False. When is_multipart() returns False, the payload should be a string object. return get_body(msg.get_payload(0)) else: '''Return the current payload, which will be a list of Message objects when is_multipart() is True,  or a string when is_multipart() is False. If the payload is a list and you mutate the list object, you modify the message’s payload in place.''' return msg.get_payload(None , decode=True)

   

解析郵件內(nèi)容并提交禪道

# 解析郵件內(nèi)容并調(diào)用禪道提交(上一篇文章結(jié)合來(lái)看)def parse1(body): pattern = re.compile('Dear Colleagues,<br>(.*?)Thanks and Regards,<br>', re.S) pattern1 = re.compile('black">(.*?)<o:p>', re.S) pattern2=re.compile(';">\r(.*?);\r<',re.S) lists = re.findall(pattern, body) print("*"*10) lists = str(lists[0]).replace("\n", "").split("<br>") print(lists) resultlist = [] for i in range(len(lists)): if (len(lists[i]) > 1): resultlist.append(lists[i]) print(resultlist) id = resultlist[1] ids=str(str(resultlist[1]).split(":")[1]).lstrip() Subject = resultlist[2] Subjects="[FeedBack-"+str(str(resultlist[1]).split(":")[1]).lstrip() + "]--"+str(str(resultlist[2]).split(":")[1]) Creator = resultlist[3] Creators = str(str(resultlist[3]).split(":")[1]) Category = resultlist[4] IssueCategory = resultlist[5] if ("Low" in resultlist[6]): Severity = "4" Severity_desc = "Severity: Low (Limited business impact)" if ("Medium" in resultlist[6]): Severity = "3" Severity_desc = "Severity: Medium (Functional but impact operations)" if ("High" in resultlist[6]): Severity = "2" Severity_desc = "Severity: High (Major system outage)" Module = resultlist[7] if('black">' in resultlist[8] and '<o:p>' in resultlist[8]): Details = str(re.findall(pattern1, resultlist[8])[0]).replace("&quot;", "\"") if(';">\r' in resultlist[8] and ';\r<' in resultlist[8]): Details = str(re.findall(pattern2, resultlist[8])[0]).replace("&quot;", "\"") link = resultlist[9] steps = id + "<br>" + Subject + "<br>" + Creator + "<br>" + Category + "<br>" + IssueCategory + "<br>" + Severity_desc + "<br>" + Module + "<br>" + Details + "<br>" + link print(steps.replace("<br>", "\n")) sql="SELECT * FROM zt_bug WHERE title LIKE \"[FeedBack-"+str(ids)+"%\"" print(sql) if(executesql(sql,envs)>=1): print("there is an record exists!!!") #add_bug(Subjects, Creators, Severity, steps,envs) else: add_bug(Subjects,Creators,Severity,steps,envs)
   

提交bug至禪道

#提交bug到禪道的方法def add_bug(a,b,c,d,e): #此方法可以與上一遍文章結(jié)合在一起提交到禪道 pass

關(guān)于Python中怎么提取郵件內(nèi)容就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI