0

I have been working on a small email utility in Python after following an online tutorial. The only issue seems to be the data I am printing is None. For example, the sender and subject of the email, when printed, are None. Here is my code:

import imaplib
import email

class email_account:
    #u: email username
    #domain: email domain
    #pwd: email account password
    #smtp_server: SMTP server for email account. I.e. "imap.gmail.com"
    #smtp_port: SMTP server port number. I.e. 993
    def __init__(self, u, domain, pwd, smtp_server, smtp_port):
            self.u = u
            self.domain = domain
            self.pwd = pwd
            self.smtp_server = smtp_server
            self.smtp_port = smtp_port

    #extracts information from an email
    def read_email(self, mail):
            return None

    #open the inbox for the email account and get the IDs of all emails
    def open_inbox(self, mail):
            mail.select("inbox")
            type, data = mail.search(None, "all")
            mail_ids = data[0]
            id_list = mail_ids.split()

            #get ID of first and last email
            first_id = int(id_list[0])
            last_id = int(id_list[-1])

            print("First ID: " + str(first_id) + " -> " + str(int(last_id)))

            #iterate through all emails retrieved from the inbox
            for x in range(first_id, last_id, 1):
                    print("RAN")
                    t, d = mail.fetch(str(x), "(RFC822)")
                    for message_parts in d:
                            print(isinstance(message_parts[1], str))
                            message = email.message_from_string(str(message_parts[1]))
                            subject = message["subject"]
                            sender = message["from"]
                            print("From: " + str(sender) + "\n")
                            print("Subject: " + str(subject) + "\n")

    #login to the email account with the provided credentials
    def login(self):
            mail = imaplib.IMAP4_SSL(self.smtp_server)
            mail.login(self.u, self.pwd)
            self.open_inbox(mail)

new_email = email_account("my_email", "@gmail.com", "password", "imap.gmail.com", 993)
new_email.login()

'print("From: " + str(sender) + "\n")' prints out From: None and print("Subject: " + str(subject) + "\n") prints out Subject: None. What is going on here?

nedrathefr
  • 215
  • 1
  • 5
  • 13
  • What is being stored in the `message` variable? Do you have data in it if you try to print it? – Zack Tarr Dec 28 '17 at 20:21
  • You can print out `message.items()` and you can see what's contained in it. – Tai Dec 28 '17 at 21:03
  • @ZackTarr @Tai There is a very long, mostly HTML, formatted payload. I see some fields, but it does not look like a well formatted `Message` object – nedrathefr Dec 28 '17 at 21:23

0 Answers0