1

import email import imaplib import os

class FetchEmail():

    connection = None
    error = None
    mail_server="outlook.office365.com"
    username="me@domain.com"
    password="'Password'"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
    self.connection = imaplib.IMAP4_SSL(mail_server)
    self.connection.login(username, password)
    self.connection.select(readonly=False) # so we can mark mails as read

def close_connection(self):
    """
    Close the connection to the IMAP server
    """
    self.connection.close()

def save_attachment(self, msg, download_folder="/tmp"):
    """
    Given a message, save its attachments to the specified
    download folder (default is /tmp)

    return: file path to attachment
    """
    att_path = "No attachment found."
    for part in msg.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue

        filename = part.get_filename()
        att_path = os.path.join(download_folder, filename)

        if not os.path.isfile(att_path):
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()
    return att_path

def fetch_unread_messages(self):
    """
    Retrieve unread messages
    """
    emails = []
    (result, messages) = self.connection.search(None, 'UnSeen')
    if result == "OK":
        for message in messages[0].split(' '):
            try: 
                ret, data = self.connection.fetch(message,'(RFC822)')
            except:
                print ("No new emails to read.")
                self.close_connection()
                exit()

            msg = email.message_from_string(data[0][1])
            if isinstance(msg, str) == False:
                emails.append(msg)
            response, data = self.connection.store(message, '+FLAGS','\\Seen')

        return emails

    self.error = "Failed to retreive emails."
    return emails

I have the above code currently, and at line 12 it says self is not defined. What could be the reason for this error. I think self is defined below that line in the init function.

qwerty
  • 887
  • 11
  • 33

1 Answers1

0

Well, just by looking at the code, I can see inconsistent indentation right from the start - this is probably your main problem. Try defining your functions within the FetchEmail class.

Secondly, change the init function to:

def __init__(self, mail_server=mail_server, username=username, password=password):

this is effectively just applying default values to the init function. Lastly, to us the save_attachment function /save_attachment(self, msg, download_folder) within the class, you will either need to call it within the init function or within the top-level of the scipt (outside the class definition)

  • Within class definition (within init): self.save_attatchment(msg,download_folder)
  • Within top level: after creating an FetchEmail object using fe = FetchEmail() then you could call the save_attachment function like this: attatchment_path = fe.save_attachment()

This is how I would implement the init:

class FetchEmail():
    def __init__(self,
        mail_server="outlook.office365.com", 
        username="rnandipati@jmawireless.com",
        password="'RNjma17!'"):

        self.error = None
        self.connection = None
        self.mail_server = mail_server
        self.username = username
        self.password = password
        self.connection = imaplib.IMAP4_SSL(mail_server)
        self.connection.login(username, password)
        self.connection.select(readonly=False) # so we can mark mails as readread

    def close_connection(self): ...

just take note, if you do this, just remember to change the reference of all your functions to self.password, self.error etc.

I do not know whether this would work. Maybe take a look at this. I think it is your best bet.

All the best!

Community
  • 1
  • 1
Iggydv
  • 166
  • 2
  • 12