Reading email body text using python 3.6

2.3k Views Asked by At

I am trying to get exact text that is sent on my gmail but i am also getting someother value also, following is my code.

import imaplib

server = imaplib.IMAP4_SSL ('imap.gmail.com', 993)
username = 'email'
password = 'pass'
server.login(username, password)
stat , content = server.select('Inbox')
stat , data = server.fetch(content[0],'(UID BODY[TEXT])')
print (data[0][1].decode())
server.close()
server.logout()

In this case my output is

--001a11443f6015ac310559254049
Content-Type: text/plain; charset="UTF-8"

hello

--001a11443f6015ac310559254049
Content-Type: text/html; charset="UTF-8"

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

--001a11443f6015ac310559254049--

But my message was only hello

1

There are 1 best solutions below

0
On

I have used this method.


v = data[0][1].decode()
w = v.split('\n')

message = w[5]

Obviously, my message does not have any newline. But if you have them you can try this.


v = data[0][1].decode()
w = v.split('\n')

message = ''

for i in range(i-5,(len(w)-2)):
   message = message + w[i] + '\n'

I'm pretty new to Python so I don't have advanced level knowledge but right now this one works perfectly.

Hope it helps.