Python Forum
Get sender of email - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Get sender of email (/thread-38854.html)



Get sender of email - Pedroski55 - Dec-03-2022

I am trying to make imaplib work for me. I read several online guides and did what they said.

Yesterday, I could get the subject and the sender, but not the body or the attachment.

1 step at a time.

Today, I can get the subject:

import imaplib
import email
from email.header import decode_header
import getpass
import os
import webbrowser
import base64


def getSubject(em):
    for response in em:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])
            # decode the email subject
            subject, encoding = decode_header(msg["Subject"])[0]
            if isinstance(subject, bytes):
                # if it is bytes, decode to str
                subject = subject.decode(encoding)
    return subject

imap_server = "imap.qq.com"
# sender of interest = [email protected]
sender_of_interest = '[email protected]'
email_address = input('Enter your email for qq mail ')
# imap password
password = input('Enter your imap password ... ')
# if no other port is given standard IMAP4-over-SSL port = 993 
M = imaplib.IMAP4_SSL(imap_server)
M.login(email_address, password)
M.select('INBOX')
# this should get only the messages from [email protected]
status, numbers = M.search(None, '(FROM "[email protected]")')
print(f'emails IDs from {sender_of_interest} are', numbers) 
# get an email
status, myemail = M.fetch("100", "(RFC822)")  # fetches the email using it's ID
# get the email subject
subject = getSubject(myemail)
This corectly gives:

Output:
>>> subject 'Excel_file'
But this:

def getSender(em):
    for response in em:        
        if isinstance(response, tuple):
            msg = email.message_from_bytes(response[1])
            # decode email sender
            From, encoding = decode_header(msg.get("From"))[0]
            if isinstance(From, bytes):
                From = From.decode()        
    return From
gets me a quotation mark, that's all:

>>> sender = getSender(myemail)
>>> sender
'"'
>>> 
I copied what I found on various websites for using imaplib, but I don't get the sender.

Any tips please??