Skip to content

Instantly share code, notes, and snippets.

@briglx
Last active May 7, 2024 11:24
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save briglx/3d5aa90144a4696be61b3991aa339cc5 to your computer and use it in GitHub Desktop.
Save briglx/3d5aa90144a4696be61b3991aa339cc5 to your computer and use it in GitHub Desktop.
Extract Email from Outlook with Python
#!/usr/bin/python
"""Script to fetch email from outlook."""
import win32com.client
def extract(count):
"""Get emails from outlook."""
items = []
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the inbox
messages = inbox.Items
message = messages.GetFirst()
i = 0
while message:
try:
msg = dict()
msg["Subject"] = getattr(message, "Subject", "<UNKNOWN>")
msg["SentOn"] = getattr(message, "SentOn", "<UNKNOWN>")
msg["EntryID"] = getattr(message, "EntryID", "<UNKNOWN>")
msg["Sender"] = getattr(message, "Sender", "<UNKNOWN>")
msg["Size"] = getattr(message, "Size", "<UNKNOWN>")
msg["Body"] = getattr(message, "Body", "<UNKNOWN>")
items.append(msg)
except Exception as ex:
print("Error processing mail", ex)
i += 1
if i < count:
message = messages.GetNext()
else:
return items
return items
def show_message(items):
"""Show the messages."""
items.sort(key=lambda tup: tup["SentOn"])
for i in items:
print(i["SentOn"], i["Subject"])
def main():
"""Fetch and display top message."""
items = extract(5)
show_message(items)
if __name__ == "__main__":
main()
@oladimejiolapoju
Copy link

Hi, i tried this code but it is not working. i keep getting the exception error message "Error processing mail". could you have a look at the code again

@briglx
Copy link
Author

briglx commented Jun 30, 2019

Hi, What line is the code failing? What versions are you running for Python and outlook. What OS are you running on? Can you verify the version of the win32com driver?

@oladimejiolapoju
Copy link

hi thanks for the response, first the script complained about parenthesis for the print function, which i adjusted then it complained also about line 7 the unicode the i got this error. this will be line 34 in your code.
File "ext_email.py", line 37, in extract
message = messages.GetNext()
File "<COMObject >", line 4, in GetNext

find below response to your questions:
(Outlookvenv) C:\Users\o.olapoju\Documents\code3\Outlook>python --version
Python 3.7.3
i am using outlook 2016
running it on windows 10
cannot seem to find the version of win32com driver but the version of pywin32 that i installed was 224

@allanpedroni
Copy link

the same error happen here.."Error processing mail"
Python 3.7.4
Outlook 360;
windows 10;

@olucca
Copy link

olucca commented Feb 1, 2020

??

@steveandpeggyb
Copy link

steveandpeggyb commented Feb 5, 2020

For Python 3.7, Update line 7 above to use

return str(s).encode('utf-8')

instead of

return unicode(s, 'utf-8')

@briglx
Copy link
Author

briglx commented Feb 6, 2020

Looks like this was originally written for Python 2. I've updated the gist. Be sure to include python -m pip install pywin32

@ukrainian-serge
Copy link

Excellent and very helpful code.
I'm fairly new and if you would be so kind as to point me in the direction of how to learn win32. For example, how did you know which args(eg "Subject", "<UNKNOWN>") to pass to gettattr to the message object? I am looking for ways to explore these COM objects but am a little lost in the weeds.

Any help would be appreciated.

@holyroli
Copy link

holyroli commented Oct 9, 2020

Thank you, this helped me!

@SureshExpleo
Copy link

Hai everyone. I am SURESH the python programmer,

From the above program in the line no:9 ,we use 'Outlook. Application'

In Case if the user can download an Outlook Application from MS Office setupo365prox64bit.exe ,then how to get 'Outlook. Application'.
I am excepting the solution by anyone.

Thanks and Regards...
SURESH R

@briglx
Copy link
Author

briglx commented Apr 8, 2021

@SureshExpleo
Copy link

Thank u briglx ...

@SureshExpleo
Copy link

haiii briglx.......If u don't mind can u explain with python example

I launch the app using os module....After that how to get oulook mail

Thanks and Regards..
SURESH R

@wandabwa2004
Copy link

What if you have more than one account in addition to the default one. How do I access the Inbox of the other mailbox as its not the default one?

@briglx
Copy link
Author

briglx commented May 12, 2021

@wandabwa2004 you can iterate over your accounts with

for account in outlook.Session.Accounts:
    if account.DisplayName == 'my_other_account@hotmail.com':
        current_account = account

@shilpasethia
Copy link

Hi, could you please tell me how in the above code I can extract the email by it's time rather than looking at the most recent email.

@jstorrs
Copy link

jstorrs commented Mar 27, 2023

Thanks for the helpful gist!

FYI there's an error on lines 16-23. The message = dict() assignment discards the message object obtained from Outlook and replaces it with an empty dict() and then tries to extract attributes from the empty dict. The following change worked for me:

...
while message:
    try:
        msg = dict()
        msg["Subject"] = getattr(message, "Subject", "<UNKNOWN>")
        msg["SentOn"] = getattr(message, "SentOn", "<UNKNOWN>")
        msg["EntryID"] = getattr(message, "EntryID", "<UNKNOWN>")
        msg["Sender"] = getattr(message, "Sender", "<UNKNOWN>")
        msg["Size"] = getattr(message, "Size", "<UNKNOWN>")
        msg["Body"] = getattr(message, "Body", "<UNKNOWN>")
        items.append(msg)
    except Exception as ex:
        ...

I'll check the documentation (windows platform is not my forte), but do you have any hints on saving the message as a *.msg file? Basically, I'm trying to automate dragging emails that match certain patterns out into Explorer.

Edit: looks like you just call message.SaveAs("path/to/outputfile.msg")

https://stackoverflow.com/questions/33235626/saving-to-msg-file-in-python-or-alternatively-sending-mail-to-the-file-system

@briglx
Copy link
Author

briglx commented Mar 28, 2023

@jstorrs thanks for the catch. I'll make the change. As for automating emails, I'm not familiar with how to create *.msg files. I'd be curious if Power Platform. https://powerplatform.microsoft.com/en-us/

@Gui-mp8
Copy link

Gui-mp8 commented Apr 22, 2023

If would not bother you, i have 2 questions:

1 - This code only works if i have a corporative account ?
2 - The email must be in my pc outlook app, right?

@nicoquant
Copy link

How have you known that Subject, Body, GetFirst, and GetLast were attributes of the object message?

@briglx
Copy link
Author

briglx commented Oct 16, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment