使用Python从Gmail提取信息

问题描述 投票:5回答:1

我已经找到解决方法,以从Gmail邮箱中选定的已接收电子邮件中提取有用的信息

此示例的目的是获取从时事通讯发送的所有提供每月石油价格的邮件。您可以在EIA网站上免费订阅这样的新闻通讯。所有此类新闻简报都到达我的Gmail邮箱的同一文件夹中,并以“ $”开头。

电子邮件内容就是这样

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9jdElhZi5wbmcifQ==” alt =“在此处输入图像描述”>

并且我的目标是编写一个脚本,以获取最近的10封此类电子邮件(最近10个月),并绘制美国不同地区的石油价格随时间变化的图表。

python gmail extract imaplib
1个回答
20
投票

Python email库会有所帮助。

import email, getpass, imaplib, os, re
import matplotlib.pyplot as plt

此目录是您保存附件的位置

 detach_dir = "F:\OTHERS\CS\PYTHONPROJECTS"  

然后您的脚本向用户(或您自己)询问帐户功能

user = raw_input("Enter your GMail username --> ")
pwd = getpass.getpass("Enter your password --> ")

然后连接到gmail imap服务器并登录

m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user, pwd)

选择一个文件夹,您可以使用整个收件箱

m.select("BUSINESS/PETROLEUM")    

一个人应该使用m.list()来获取所有邮箱。搜索来自指定发件人的所有电子邮件,并选择邮件ID:

resp, items = m.search(None, '(FROM "[email protected]")')
items = items[0].split()  

my_msg = [] # store relevant msgs here in please
msg_cnt = 0
break_ = False

我需要最后一封电子邮件,因此我正在使用items[::-1]

for emailid in items[::-1]:

    resp, data = m.fetch(emailid, "(RFC822)")

    if ( break_ ):
        break

    for response_part in data:

      if isinstance(response_part, tuple):
          msg = email.message_from_string(str(response_part[1]))
          varSubject = msg['subject']
          varDate = msg['date']

我只想要以$开头的那些

          if varSubject[0] == '$':
              r, d = m.fetch(emailid, "(UID BODY[TEXT])")

              ymd = email.utils.parsedate(varDate)[0:3]
              my_msg.append([ email.message_from_string(d[0][1]) , ymd ])

              msg_cnt += 1

我只需要N = 100条最后一条消息

              if ( msg_cnt == 100 ):
                  break_ = True

l = len(my_msg)
US, EastCst, NewEng, CenAtl, LwrAtl, Midwst, GulfCst, RkyMt, WCst, CA = 
[0]*l, [0]*l, [0]*l, [0]*l, [0]*l, [0]*l, [0]*l, [0]*l, [0]*l, [0]*l 
absc = [k for k in range(len(my_msg))]
dates = [str(msg[1][2])+'-'+str(msg[1][3])+'-'+str(msg[1][0]) for msg in my_msg]
cnt = -1

for msg in my_msg:

    data = str(msg[0]).split("\n")
    cnt+=1
    for c in [k.split("\r")[0] for k in data[2:-2]]: 

使用正则表达式获取相关信息

        m = re.match( r"(.+)(=3D\$)(.+)" , c )  
        if( m == None ):
            continue 

        country, na, price = m.groups()

        if ( country == "US" or country == "USA" ) :
            US[cnt] = float(price)
        elif( country == "NewEng" ) :
            EastCst[cnt] = float(price)    
        elif( country == "EastCst" ) :
            NewEng[cnt] = float(price)  
        elif( country == "EastCst" ) :
            CenAtl[cnt] = float(price) 
        elif( country == "EastCst" ) :
            LwrAtl[cnt] = float(price)
        elif( country == "EastCst" ) :
            Midwst[cnt] = float(price)
        elif( country == "EastCst" ) :
            GulfCst[cnt] = float(price)
        elif( country == "EastCst" ) :
            RkyMt[cnt] = float(price)
        elif( country == "EastCst" ) :
            WCst[cnt] = float(price)
        elif( country == "EastCst" ) :
            CA[cnt] = float(price)

用美国价格绘制所有这些曲线

plt.plot( absc, US )

plt.plot( absc, EastCst )    
plt.plot( absc, NewEng, '#251BE0' )    
plt.plot( absc, EastCst, '#1BE0BF' )
plt.plot( absc, CenAtl, '#E0771B' )
plt.plot( absc, LwrAtl, '#CC1BE0' )
plt.plot( absc, Midwst, '#E01B8B' ) 
plt.plot( absc, GulfCst, '#E01B3F' )
plt.plot( absc, RkyMt )
plt.plot( absc, WCst )
plt.plot( absc, CA )

plt.legend( ('US', 'EastCst', 'NewEng' , 'EastCst', 'CenAtl', 'LwrAtl', 'Midwst', 'GulfCst', 'RkyMt', 'WCst', 'CA')  )
plt.title('Diesel price')
locs,labels = plt.xticks(absc, dates)
plt.show()

一些相关的有趣主题在这里

Get only new emails

Fetch mail body

Forward emails with attachment

Fetch body emails in gmail

结果仅在三个区域出现

“我们的价格”

© www.soinside.com 2019 - 2024. All rights reserved.