Last active
May 7, 2024 11:24
-
-
Save briglx/3d5aa90144a4696be61b3991aa339cc5 to your computer and use it in GitHub Desktop.
Extract Email from Outlook with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
@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/
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?
How have you known that Subject, Body, GetFirst, and GetLast were attributes of the object message?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the helpful gist!
FYI there's an error on lines 16-23. The
message = dict()
assignment discards themessage
object obtained from Outlook and replaces it with an emptydict()
and then tries to extract attributes from the empty dict. The following change worked for me: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