Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9120265
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T05:35:18+00:00 2026-06-17T05:35:18+00:00

I have come through solutions to extract useful information from selected received emails in

  • 0

I have come through solutions to extract useful information from selected received emails in Gmail mailbox.

Aim in this example is to fetch all mails sent from a newsletter providing monthly prices for petroleum. You can freely subscribe to such a newsletter on EIA website. All such newsletter arrive in same folder in my gmail mailbox, and begin with “$”.

Content for emails is like that

enter image description here

and my objective is to write a script that fetch the 10 last such emails (last 10 months) and plot petroleum prices for the different US regions with respect to time.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T05:35:19+00:00Added an answer on June 17, 2026 at 5:35 am

    Python email library will help.

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

    This directory is where you will save attachments

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

    Your script then asks user (or yourself) for account features

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

    Connect then to the gmail imap server and login

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

    Select one folder, you could use the whole INBOX instead

    m.select("BUSINESS/PETROLEUM")    
    

    One should use m.list() to get all the mailboxes. Search for all emails coming from specified sender and
    select the mail ids:

    resp, items = m.search(None, '(FROM "EIA_eLists@eia.gov")')
    items = items[0].split()  
    
    my_msg = [] # store relevant msgs here in please
    msg_cnt = 0
    break_ = False
    

    I want the last emails, so that I am using 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']
    

    I want only the ones beginning with $

              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
    

    I want only the N=100 last messages

                  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]]: 
    

    Use regular expressions to fetch relevant information

            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)
    

    Plot all these curves with US prices

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

    Some related interesting topics are here

    Get only new emails

    Fetch mail body

    Forward emails with attachment

    Fetch body emails in gmail

    Results are here for three areas only

    us prices

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have looked through several sites for any useful documentation and have come up
I am going through this tutorial about PDO and have come to the point
I have a MessageInspector which logs the messages that come through? What is the
I have come to know from book that for declaring a structure variable it
I have come across several solutions here and across the web but none seem
I have come across an annoying problem. I have made a system and now
I have come across scripts that use: isset($_POST['submit']) as well as code that uses:
I have come across the following basic Tree conflict: Local add, incoming add upon
I have come across many articles which warn against using links to provide logout
I have come across loop-unrolling but what other types of compiler optimization are there

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.