Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read emails python 3.
#1
Hello guys.I am pretty noob in python.I wanna make a python email through cli cuz I love terminal and cmd and stuff like that.However none of the examples that I find on google work.

I can send messages but I can't read them properly.Please someone give me an example.Preferable for gmail.com

Thanks in advance.
Reply
#2
Quote:none of the examples that I find on google work.
If this were true, I'd say that it wasn't possible.
Please:
  • make an attempt:
  • show your code
  • show any error messages complete and unaltered
  • explain where you are having trouble
  • Do all above, and we will be glad to help
Reply
#3
(Jan-26-2019, 11:43 AM)Larz60+ Wrote:
Quote:none of the examples that I find on google work.
If this were true, I'd say that it wasn't possible.
Please:
  • make an attempt:
  • show your code
  • show any error messages complete and unaltered
  • explain where you are having trouble
  • Do all above, and we will be glad to help

Here we go.
This one just stays opened with out doing anything.
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')

mail.login('myemail', 'password')


mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")

i = len(data[0].split()) 
for x in range(i):
 latest_email_uid = data[0].split()[x] 
 result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')

 raw_email = email_data[0][1]

raw_email_string = raw_email.decode('utf-8')

email_message = email.message_from_string(raw_email_string)

for part in email_message.walk():
 if part.get_content_type() == "text/plain": 
  body = part.get_payload(decode=True)
  save_string = str("D:Dumpgmailemail_" + str(x) + ".eml")

  myfile = open(save_string, 'a')
  myfile.write(body.decode('utf-8'))

  myfile.close()
 else:
  continue
Reply
#4
Fixed indentation (PEP8 - 4 spaces per indent level)
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
 
mail.login('myemail', 'password')
 
 
mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")
 
i = len(data[0].split()) 
for x in range(i):
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
 
    raw_email = email_data[0][1]
 
raw_email_string = raw_email.decode('utf-8')
 
email_message = email.message_from_string(raw_email_string)
 
for part in email_message.walk():
    if part.get_content_type() == "text/plain": 
        body = part.get_payload(decode=True)
        save_string = str("D:Dumpgmailemail_" + str(x) + ".eml")
 
        with open(save_string, 'a') as myfile:
            myfile.write(body.decode('utf-8'))
Also simplified your save routine

Not sure if lines 19 and 21 are part of for loop or not.
Looked at examples here: https://docs.python.org/3/library/email.examples.html
I haven't used this package, so perhaps you can compare to these examples.
Reply
#5
(Jan-26-2019, 08:26 PM)Larz60+ Wrote: Fixed indentation (PEP8 - 4 spaces per indent level)
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
 
mail.login('myemail', 'password')
 
 
mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")
 
i = len(data[0].split()) 
for x in range(i):
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
 
    raw_email = email_data[0][1]
 
raw_email_string = raw_email.decode('utf-8')
 
email_message = email.message_from_string(raw_email_string)
 
for part in email_message.walk():
    if part.get_content_type() == "text/plain": 
        body = part.get_payload(decode=True)
        save_string = str("D:Dumpgmailemail_" + str(x) + ".eml")
 
        with open(save_string, 'a') as myfile:
            myfile.write(body.decode('utf-8'))
Also simplified your save routine

Not sure if lines 19 and 21 are part of for loop or not.
Looked at examples here: https://docs.python.org/3/library/email.examples.html
I haven't used this package, so perhaps you can compare to these examples.
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
  
mail.login('[email protected]', 'pass')
  
  
mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")
  
i = len(data[0].split()) 
for x in range(i):
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
  
    raw_email = email_data[0][1]
  
    raw_email_string = raw_email.decode('utf-8')
  
    email_message = email.message_from_string(raw_email_string)
    print(email_message)
    break
  
for part in email_message.walk():
    if part.get_content_type() == "text/plain": 
        body = part.get_payload(decode=True)
        save_string = str("D:Dumpgmailemail_" + str(x) + ".eml")
  
        with open(save_string, 'a') as myfile:
            myfile.write(body.decode('utf-8'))
Done.Now everything works.Those 2 lines should've been part of for loop but in original code of mine they weren't.Thanks for bringing my atention to it.have a good day.

Nevermind...
MIME-Version: 1.0
Date: Sun, 27 Jan 2019 12:18:51 +0200
Message-ID: <CAK_qYVGw+UC7Ar9FhU+YRKQC8hXqs=tJzXW6_CvXsaJjzOJwSA@mail.gmail.com>
Subject: Muie
From: Wind Bullet <[email protected]>
To: [email protected]
Content-Type: multipart/alternative; boundary="0000000000000765de05806de3c2"

--0000000000000765de05806de3c2
Content-Type: text/plain; charset="UTF-8"

Muiescp

--0000000000000765de05806de3c2
Content-Type: text/html; charset="UTF-8"

<div dir="auto">Muiescp</div>

--0000000000000765de05806de3c2--

Muiescp
I have this output.How can I just the content in <div dir="auto"></div> Bassicaly the message only.Also if the possible the subject but not neccesary.

(Jan-27-2019, 10:21 AM)negru555 Wrote:
(Jan-26-2019, 08:26 PM)Larz60+ Wrote: Fixed indentation (PEP8 - 4 spaces per indent level)
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
 
mail.login('myemail', 'password')
 
 
mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")
 
i = len(data[0].split()) 
for x in range(i):
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
 
    raw_email = email_data[0][1]
 
raw_email_string = raw_email.decode('utf-8')
 
email_message = email.message_from_string(raw_email_string)
 
for part in email_message.walk():
    if part.get_content_type() == "text/plain": 
        body = part.get_payload(decode=True)
        save_string = str("D:Dumpgmailemail_" + str(x) + ".eml")
 
        with open(save_string, 'a') as myfile:
            myfile.write(body.decode('utf-8'))
Also simplified your save routine

Not sure if lines 19 and 21 are part of for loop or not.
Looked at examples here: https://docs.python.org/3/library/email.examples.html
I haven't used this package, so perhaps you can compare to these examples.
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
  
mail.login('[email protected]', 'pass')
  
  
mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")
  
i = len(data[0].split()) 
for x in range(i):
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
  
    raw_email = email_data[0][1]
  
    raw_email_string = raw_email.decode('utf-8')
  
    email_message = email.message_from_string(raw_email_string)
    print(email_message)
    break
  
for part in email_message.walk():
    if part.get_content_type() == "text/plain": 
        body = part.get_payload(decode=True)
        save_string = str("D:Dumpgmailemail_" + str(x) + ".eml")
  
        with open(save_string, 'a') as myfile:
            myfile.write(body.decode('utf-8'))
Done.Now everything works.Those 2 lines should've been part of for loop but in original code of mine they weren't.Thanks for bringing my atention to it.have a good day.

Nevermind...
MIME-Version: 1.0
Date: Sun, 27 Jan 2019 12:18:51 +0200
Message-ID: <CAK_qYVGw+UC7Ar9FhU+YRKQC8hXqs=tJzXW6_CvXsaJjzOJwSA@mail.gmail.com>
Subject: Muie
From: Wind Bullet <[email protected]>
To: [email protected]
Content-Type: multipart/alternative; boundary="0000000000000765de05806de3c2"

--0000000000000765de05806de3c2
Content-Type: text/plain; charset="UTF-8"

Muiescp

--0000000000000765de05806de3c2
Content-Type: text/html; charset="UTF-8"

<div dir="auto">Muiescp</div>

--0000000000000765de05806de3c2--

Muiescp
I have this output.How can I just the content in <div dir="auto"></div> Bassicaly the message only.Also if the possible the subject but not neccesary.




I did this and now I can get the mail.I also think I know how to obtain the subject.Thanks for help.
import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.gmail.com')
  
mail.login('[email protected]', 'DidAnyoneHopedMyPasswordIsHereLeft?')
  
  
mail.list() 
mail.select('inbox') 
result, data = mail.uid('search', None, "ALL")
  
i = len(data[0].split()) 
for x in range(i):
    latest_email_uid = data[0].split()[x] 
    result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
  
    raw_email = email_data[0][1]
  
    raw_email_string = raw_email.decode('utf-8')
  
    email_message = email.message_from_string(raw_email_string)
  
    for part in email_message.walk():
        if part.get_content_type() == "text/plain": 
            body = part.get_payload(decode=True)
            messajbody = body.decode('utf-8')
            messajbody = messajbody.split("<div dir=\"auto\">")
            messajbody = messajbody[0].replace("\n","")
            print(messajbody)
T/C
Reply
#6
(Jan-27-2019, 10:21 AM)negru555 Wrote: How can I just the content in <div dir="auto"></div> Bassicaly the message only.Also if the possible the subject but not neccesary.
Write your own parser,example BS for html and regex for rest.
from bs4 import BeautifulSoup
import re

email = '''\
MIME-Version: 1.0
Date: Sun, 27 Jan 2019 12:18:51 +0200
Message-ID: <CAK_qYVGw+UC7Ar9FhU+YRKQC8hXqs=tJzXW6_CvXsaJjzOJwSA@mail.gmail.com>
Subject: Muie
From: Wind Bullet <[email protected]>
To: [email protected]
Content-Type: multipart/alternative; boundary="0000000000000765de05806de3c2"

--0000000000000765de05806de3c2
Content-Type: text/plain; charset="UTF-8"

Muiescp

--0000000000000765de05806de3c2
Content-Type: text/html; charset="UTF-8"

<div dir="auto">Muiescp</div>

--0000000000000765de05806de3c2--

Muiescp'''

soup = BeautifulSoup(email, 'lxml')
subject = re.search(r'Subject: (.*)', email).group(1)
email_from = re.search(r'From: (.*)', email).group(1)
message = soup.find('div')
print(subject)
print(email_from)
print((message.text))
Output:
Muie Wind Bullet <[email protected]> Muiescp
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020