Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

receiving emails with python api O365

I am just starting out in Python and I am trying to accomplish a manual task I have heard is on the simpler side to accomplish with python. My company uses Office 365 for their emails and I want to retrieve an email attachment and store it locally so I can save time . So far have established how to send a simple email, call the names of the folders in my account but I cannot figure out how to read any specific email .

my idea goes a little like this ,

from O365 import Account, message,mailbox

credentials =  ('username', 'given password')

account = Account(credentials)
mailbox = account.mailbox()
mail_folder = mailbox.inbox_folder()
mail_folder = mailbox.get_folder(folder_name='Inbox')
print(mail_folder)
#_init__(*,parent= Inbox, con=None,**kwargs)
Message_body = message.body()
message.get_subject('email subject here!')
print(Message.body)

right now I am lost and trying anything within the O365 documentation page but the message module does not have the attribute subject according to how I am using it . Any guidance would be much appreciated

like image 637
Ehigie Edokpayi Avatar asked Nov 22 '25 12:11

Ehigie Edokpayi


1 Answers

From your example - it's not clear if you are authenticated or not...

If you are then you will be able to list the mailbox folders. In the case below - you can access the inbox and then list the sub-folders:

from O365 import Account, Connection,  MSGraphProtocol, Message, MailBox, oauth_authentication_flow

scopes=['basic', 'message_all']
credentials=(<secret>, <another secret>)
account = Account(credentials = credentials)

if not account.is_authenticated:  # will check if there is a token and has not expired
    account.authenticate(scopes=scopes)

account.connection.refresh_token()mailbox = account.mailbox()
inbox = mailbox.get_folder(folder_name='Inbox')
child_folders = inbox.get_folders(25)
for folder in child_folders:
    print(folder.name, folder.parent_id)

This part will allow you to list folders (and also messages).

If I look at your code - it looks as though you are trying to do both?

Try doing something like the following to get the hang of paging through your inbox:

for message in inbox.get_messages(5):
    if message.subject == 'test':
        print(message.body)

Note that I'm looping through the first 5 messages in the inbox looking for a message with subject 'test'. If it finds the message - then it prints the body.

Hopefully this will shed a little light.

like image 165
Chris Mellor Avatar answered Nov 25 '25 04:11

Chris Mellor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!