Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get sender of email
#1
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??
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  get sender IP on UDP server? korenron 2 2,697 Jun-21-2021, 03:11 PM
Last Post: korenron
  An email with inline jpg cannot be read by all email clients fpiraneo 4 3,998 Feb-25-2018, 07:17 PM
Last Post: fpiraneo
  Simple e-mail sender, that automatically changes subject for every e-mail joker 2 3,174 Aug-24-2017, 09:45 AM
Last Post: joker
  Email - Send email using Windows Live Mail cyberzen 2 5,932 Apr-13-2017, 03:14 AM
Last Post: cyberzen

Forum Jump:

User Panel Messages

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