Python中怎么提取邮件内容
发表于:2025-12-03 作者:千家信息网编辑
千家信息网最后更新 2025年12月03日,这篇文章将为大家详细讲解有关Python中怎么提取邮件内容,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。基础信息准备import imaplib, e
千家信息网最后更新 2025年12月03日Python中怎么提取邮件内容
这篇文章将为大家详细讲解有关Python中怎么提取邮件内容,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
基础信息准备
import imaplib, email,re,requests,time,pymysqlimapserver = 'smtp.office365.com'emailuser = "qa.notice@shangri-la.com"emailpasswd = "test123"#beta环境禅道地址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环境禅道地址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" #定义使用的环境
数据库连接信息
#连接数据库相关的信息: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"}数据库查询
#数据库查询操作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 0else: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') # 选择收件箱(默认) 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)') # 通过邮件id获取邮件,data是fetch到的邮件具体内容 e = email.message_from_bytes(data[0][1])解释说明与print
''' Header()类: email.header.Header(s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict') 其中参数的含义理解如下: s:标头的值,也就是对应 From、To、Subject 的值; charset:字符集格式,默认是 ASCII,但是一般指定 UTF-8 格式以兼容更多字符; header_name:标头名,就是 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("邮件的发件人是%s" % mail_from) body = str(get_body(e), encoding='ISO-8859-1') # utf-8 gb2312 GB18030解析中文日文英文 print("邮件内容是%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)
解析邮件内容并提交禅道
# 解析邮件内容并调用禅道提交(上一篇文章结合来看)def parse1(body): pattern = re.compile('Dear Colleagues,
(.*?)Thanks and Regards,
', re.S) pattern1 = re.compile('black">(.*?)', re.S) pattern2=re.compile(';">\r(.*?);\r<',re.S) lists = re.findall(pattern, body) print("*"*10) lists = str(lists[0]).replace("\n", "").split("
") 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 '' in resultlist[8]): Details = str(re.findall(pattern1, resultlist[8])[0]).replace(""", "\"") if(';">\r' in resultlist[8] and ';\r<' in resultlist[8]): Details = str(re.findall(pattern2, resultlist[8])[0]).replace(""", "\"") link = resultlist[9] steps = id + "
" + Subject + "
" + Creator + "
" + Category + "
" + IssueCategory + "
" + Severity_desc + "
" + Module + "
" + Details + "
" + link print(steps.replace("
", "\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): #此方法可以与上一遍文章结合在一起提交到禅道 pass
关于Python中怎么提取邮件内容就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
邮件
内容
信息
数据
数据库
文章
更多
环境
篇文章
主体
地址
字符
格式
知识
上一
查询
检索
不错
也就是
参数
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
海南海口软件开发工作室
分布式数据库Hadoop
安徽星灿网络技术有限公司
玩脱了手游数据库
软件开发过程中的配置管理
网络安全公司涉及的成本
工程师网络安全学习心得体会
8090网络安全门户
数据库第一道安全保障
服务器查看ftp
杭州互联网科技大会
网络技术应用结业考试
电力系统服务器配置
明光工程软件开发技术哪家好
华为服务器管理插件软件
麒麟天创网络技术有限公司
无线网络安全监管哪家价格实惠
黑客网络安全视频
东莞社交软件开发定制
微信自研数据库
汽车网络安全图片
国内软件开发大学
天津服务器维修调试多少钱
网络安全向导在哪里
委托软件开发产权
黑龙江ftp服务器租用
吃鸡如何一次上线两个服务器
云派脚本为啥显示服务器已满
学生学习网络安全教育反响
知网数据库检索式