Download All Messages & Attachments From Outlook Using Python
HTML-код
- Опубликовано: 11 сен 2024
- 👉 Explore All My Excel Solutions: pythonandvba.c...
𝗗𝗘𝗦𝗖𝗥𝗜𝗣𝗧𝗜𝗢𝗡
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
In this video, we learn how to use Python to save all messages & attachments from Outlook. This will come in handy when you want to archive old email conversations and attachments. This is a very simple process and can be implemented in just a few minutes!
🌍 𝗟𝗜𝗡𝗞𝗦:
▶ Code on GitHub: github.com/Sve...
𝗧𝗢𝗢𝗟𝗦 𝗔𝗡𝗗 𝗥𝗘𝗦𝗢𝗨𝗥𝗖𝗘𝗦
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
🆓【𝗙𝗥𝗘𝗘】Excel Add-in (𝗠𝘆𝗧𝗼𝗼𝗹𝗕𝗲𝗹𝘁): pythonandvba.c...
📊 Dashboard Excel Add-In (𝗚𝗿𝗮𝗳𝗹𝘆): pythonandvba.c...
🎨 Cartoon Charts Excel Add-In (𝗖𝘂𝘁𝗲𝗣𝗹𝗼𝘁𝘀): pythonandvba.c...
🤪 Fun Emoji Excel Add-In (𝗘𝗺𝗼𝗷𝗶𝗳𝘆): pythonandvba.c...
📑 Excel Templates: pythonandvba.c...
🎓 My Courses: pythonandvba.c...
📚 Books, Tools, and More: pythonandvba.c...
𝗖𝗢𝗡𝗡𝗘𝗖𝗧 𝗪𝗜𝗧𝗛 𝗠𝗘
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
🔗 LinkedIn: / sven-bosau
📸 Instagram: / codingisfun_official
💻 GitHub: github.com/Sve...
💬 Discord: pythonandvba.c...
📬 Contact: pythonandvba.c...
☕ 𝗕𝘂𝘆 𝗺𝗲 𝗮 𝗰𝗼𝗳𝗳𝗲𝗲?
If you want to support this channel, you can buy me a coffee here:
▶ pythonandvba.c...
*Do you have any questions or further automation ideas? Let me know in the comments! 👍*
how do i run this script automatically everyday?
which only downloads the latest emails.
@@bilalrasool8644 use the windows task scheduler. A quick Google search will point you in the right direction 'Windows Task scheduler run python files'
@@bilalrasool8644 You want to manipulate the for each loop 'for message in messages'.
is there a way of extracting the attachments and storing it into a temporary folder in python memory or maybe a blob storage in the cloud instead of storing it into a local folder ? and then from there call it with pandas to transform it into a data frame ?
thank you
Amazing, your tutorials are very productive. If I can make a suggestion, adding an ordering or dating in folder name makes a better navigational archive. Thank you!
Hi ermal gashi.
Thanks for watching the video and your suggestion.
You could also retrieve the received time from the message and use that (after formatting the date) as the folder name.
Please find your example below:
for message in messages:
subject = message.Subject
body = message.body
attachments = message.Attachments
received = (message.ReceivedTime).strftime("%Y_%m_%d")
# Create separate folder for each message
target_folder = output_dir / str(received) / str(subject)
target_folder.mkdir(parents=True, exist_ok=True)
Demo / Output (Screenshot):
www.screencast.com/t/yZl6JliqYl
I hope you like that solution.
Stack exchange failed me, but you came to the rescue. Great video and very concise!
Question though, how do you recommend dealing with multiple messages of the same name?
I know that in windows if you copy message.msg into a directory that already exists, you it automatically adds message.msg(1)
Is there some similar you can do for the directories?
Thanks for watching.
Before saving the file, you want to check in a while loop if the file already exists using the Pathlib or OS module. If it exists, increment the filename. Another option is to add a UUID or timestamp to the filename every time you save the message.
I hope it helps! Happy Coding!
Amazing tutorial, quick, easy to understands and just works :)
Great to hear! Thanks for watching and taking the time to leave a comment! :)
That’s just amazing, keep on working on this content 🙌🏻
Thank you! I will do my best!
I must say "thanks a million times" for this wonderful video...
I learnt something tremendous from this video content....
I want to know if there's a python module or library that exports emails and sends them to a remote server?
Thanks for watching and for your kind words. Right off the bat, I do not know of such a library. Happy coding! Cheers, Sven ✌️
It's very useful thanks for sharing. My ask is could you please few more information in this video.
1. Adding code: downloading the attachment from the inbox (subfolder).
2. Adding code: downloading the current date attachment from subfolder.
3. Adding code: downloading latest attachment from the subflolder.
4. Adding code: downloading all the attachments without looking specific reports from subfolder
5. Adding code: downloading the attachment with same format ex: (csv, xlx, xlsx etc.)
Thank you for watching the video. Your questions are great, but finding the time to answer them is difficult. Kindly understand that I receive many requests for individual solutions or modifications. That said, you might want to join our Discord server ( pythonandvba.com/discord ) and post your question there. Thanks for your understanding. Happy Coding!
Amazing, can you please advise how to download all the attachments from a specific Folder or subfolder, for example the inbox has OlDefaultFolders (6), unlike the subfolders
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
Hi Sven, Thanks for the video. I was looking for this.
Suggestions -
1. There can be a parameter where i will mention some rules and mail of that combination only to be downloaded like if i receive mail from particular mail id then only it should download or mail recevied on or before yesterday or by some date should be downloaded or mail with particular subject to be downloaded
2. For mail download you are giving the option of only text file is there any option to get the other format also
3. Also i receive some frequent reports from a mail where the data will be in body only and that to it will in table format any option to extract it
Last point - can you please give the same option in Excel VBA also.
Thank you for watching the video.
Those are all great suggestions! 👍
Regarding:
1. You could wrap the code into a function and pass your required parameter to the function. Inside the function, you can then perform your conditional checks (e.g. based on the received time: received = message.ReceivedTime)
2. That is possible. It really depends on your use case. For converting it to pdf, you could use the 'fpdf' module. Have a look at the following tutorial: www.geeksforgeeks.org/convert-text-and-text-file-to-pdf-using-python/
3. Here, I would also need to do some google research 😉
For a VBA based solution, definitely check out the following video form 'VBA A2Z':
ruclips.net/video/ji2jHz8YPq8/видео.html
Happy Coding!
Hi Sven,
This video really help us when we are automating outlook application. Can you please make similar video to download entire email as .msg or .text or .pdf
Thanks for watching the video & your suggestion.
just what I was looking for. awesome work mate.
Glad it was helpful. Thanks for watching & your comment! :)
Code works beautifully. Thank you sir
You're very welcome! Thank you for watching and for the comment!
Very nice. To the point! Thanks for sharing.
Glad it was helpful!
Good video, another good ideia is using the pypff lib that allow to access and parse the pst file to use with python
Thanks for watching the video & your idea. I did not know about the pypff lib. I will check it out.
Amazing video. It helped me a lot to automate my work. Only problem that I have is, I have tons of email in my Inbox so I want for loop to iterate over a certain period of dates. Could you please help me with the code?
Thanks for watching. You could use "SentOn" on the message. Here is an example: stackoverflow.com/a/38193427
Happy Coding!
@@CodingIsFun Hi, thanks for your immediate response. Is it received on inplace of senton?
really you did very well and save my time
Glad I could help! Thanks for watching! 👍
Amazing video saved my life!!! Thank you so much! Just one more question, if I just want to download attachments from today, what code should I insert below "for message in messages:"? I assume message.date() ==today?
Thanks for watching. You could use "SentOn" on the message. Here is an example: stackoverflow.com/a/38193427
Happy Coding!
@@CodingIsFun It’s showing the page is not found
@@tomx4278 should work now
@@CodingIsFun Thank you!
Thank you very much for your video, it's super helpful. I wanted to ask you, how can you download the images that are embedded in the body of the message (not attached) but rather those that are like CID? I would appreciate it if you could help me. Regards!
Thank you so much for taking the time to watch the video. I really appreciate your interest and the thought you put into your questions. Unfortunately, I receive a large volume of requests for individual solutions or modifications and it can be difficult to find the time to answer them all. If you would like, you are welcome to join our Discord server ( pythonandvba.com/discord ) and post your question there. The community there may be able to offer additional guidance or assistance. Thank you for your understanding and I hope you have a great day. Happy coding!
Unbelievable! Great job!
Thank you!
Thank you! Very helpful!!
Glad you find it helpful. As always, thanks for your comment!
Great video Thank you!
I have a few questions if you could help me with please :)
I'd remove the likes of ":" from the Mysubject string? I've tried
mysubject = subject.replace(",", "")
but i still keep getting the error
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:
When it comes to emails with illegal Windows characters for naming! Thanks
2nd Question how would i skip over emails which have NO attachments?
3rd Question How would i choose a date range say i only want emails sent on todays date?
Sorry for all the questions! appreciate any help :)
Thanks for watching.
1) You might need to replace all special characters, which are not allowed as a file name
2) Within 'message for messages:' check if there is an attachment first before saving the content to your hard drive
3) The following should get you started: received = (message.ReceivedTime).strftime("%Y_%m_%d")
Happy Coding!
@@CodingIsFun Thank you, i'll let you know how i get on. Doing some automation for work purposes!
i am working on some server and on this server outlook is not installed due to security purpose,so pywin 32 is not working throwing error pywin types error(-214722..) invalid class string can u suggest me solution .i want to access outlook and download the mail data.
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
@@CodingIsFun if u have free time , then u please solve my query as it's urgent for me.
Amazing tutorial. Thanks a lot
Happy to hear that it was useful; thank you for taking the time to leave a comment and for watching the video!
Thanks
My pleasure! Appreciate you taking the time to watch and leave a comment. -Sven ✌️
Would it be a similar process to download the outlook calendar meetings and those details? The use case would be trying to figure out how much time is being spent on different meetings over time. :)
Accessing the calendar details, e.g. meetings, is very similar.
You can access the calendar by using the value 9: GetDefaultFolder(9).Items ( docs.microsoft.com/en-us/office/vba/api/outlook.oldefaultfolders )
You might want to check out the following blog article:
pythoninoffice.com/get-outlook-calendar-meeting-data-using-python/
I noted down your idea. I might do a tutorial on that in the future.
Happy Coding!
Amazing, thank you for that!! Any idea if there is a way to get the sender's email or name? Something like sender = message.sender?
Thanks for watching. Glad you liked it. Yes, you can get the sender's email address and name using the following properties:
sender_email = message.SenderEmailAddress
sender_name = message.SenderName
See also the docs: learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.sendername
I hope it helps! Happy Coding!
no result for enterprise account outlook@@CodingIsFun
Great! This I what I have been looking for. I am a very new to python, can you do or direct me to a video how can I do this as a beginner. I mean install the python win you install in this video ad other things, please ?
Thanks for watching. Here you are: ruclips.net/video/XCvgyvBFjyM/видео.htmlsi=FCbFT5d-xoKJNX4y
Happy learning & coding! Cheers, Sven ✌️
Thanks for sharing! some of my email attachment could have another .msg files attached in it. May I know how can I extract these embedded attachment as well? Thank you!
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
sorry noob question but at 1:14, for the line of code
output_dir = Path.cwd() / "Output"
Can i ask what is the slash here and what does it do or what is it for?
Thanks for watching. Here you are: chatgpt.com/share/b2989f79-b2fa-4dd5-8308-6e526b9d1c26
I hope it helps! :)
Cheers, Sven ✌️
Thank you so much, you are amazing!
Thank you!
It seems that after my initial run, that worked flawlessly, it won't refresh the messages variable to include emails that have since been received. How can I "reset" messages to include my entire inbox at runtime? Thanks.
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you! Cheers, Sven ✌️
Great tutorial congrats!
Thank you! :)
Sven, awesome videos!
Thank you! 👍
Hello Sven, I believe your script works (the text part, not the attachments part) for plain text emails only. Is there anyway for it to also work for HTML format or simply download the EML file from the email? Thanks in advance
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding! BTW - the attachment download works for me, as shown in the video 😅
Hi Sven, what if I want to download attachment from email in form of URL then only I can download the attachment.
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you! Cheers, Sven ✌️
Amazing video, can we extract table from body of outlook email?
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
Thank you
My pleasure! Appreciate you taking the time to watch and leave a comment. 👍
Hi ! Firstly I wanna thank you for your hardwork and help. I just want to ask how can I take only excel attachments?
Thank you! What have you tried so far?
@@CodingIsFun I couldn’t tried anything. I am a newbie myself and I am struggling for loops and if else statements
@@CodingIsFun I have tried
if attachment.FileName[-3:] == “xlsx” :
But it didn’t work out
Hi, wish to ask. Instead of download the email body into ".txt" format. If i want to download the email from outlook. How should i write the code?
For example, i open my outlook and right click the email i want and press "Copy" and paste to my destination.
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
Hey
Thanks for the intro. Any tips to solving an issue of too many open items?
I need to save hundreds of docs from hundreds of mails, but ~250 is the limit.
The error message reads as such: "Your server administrator has limited the number of items you can open simultaneously. Try closing messages you have opened or removing attachments and images from unsent messages you are composing."
Thank you for watching the video and for your question. Unfortunately, I do not know how to solve that right off the bat. I would also need to search the internet for a solution. Sorry that I cannot help!
Amazing tutorial as usual. Thank you very much.
Thank you! It is always a pleasure to see your comments 😃
@@CodingIsFun I am stuck at joining path with file name (the file name has a variable part). This is my try but throws an error `merger.write(OUTPUT_DIR / f'{key}.pdf')`
@@KhalilYasser What does the error message say?
@@CodingIsFun I used this line instead `merger.write(os.path.join(os.getcwd(), OUTPUT_DIR, f'{key}.pdf'))
`. The problem is with joining path with the filename in the pathlib. Can you make a video about that topic?
@@KhalilYasser Try to convert the OUTPUT_DIR pathlib object into a string: merger.write(os.path.join(os.getcwd(), str(OUTPUT_DIR), f'{key}.pdf'))
I have already a video on joining paths using Pathlib. You might want to check it out here: ruclips.net/video/iqZ2V8qTYq8/видео.html
Thank you, It's work.
Happy to hear that it is working; thank you for taking the time to leave a comment and for watching the video!
This worked exactly as I needed but, It only downloaded one of the emails (the oldest one) from the folder I selected, is there an extra step that I might be missing to download all emails and attachments from that folder?
By the way, every single email and attachment has the exact same name, I don't know if that's got to do with it.
Thank you in advance.
Thanks for watching.
I have updated the code. Please give it another try:
github.com/Sven-Bo/download-messages-attachments-from-outlook/blob/master/retrieve_outlook_data.py
That is very useful.
Happy to hear that. Thanks for watching!
thank you. Amazing
Glad to hear you liked it! Thank you for commenting and watching.
Thanks for the video, how can I save only the attachments if the email is a central email for all incoming supplier invoices.
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
I have a project to automate incoming emails with pdfs. These pdfs in an Email has some tabular information for a webform. I have to extract this information from pdf and fill the webform. At the end I have to save the email in network directory.
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
Amazing content. Thank you for your work and help. Tried removing the part #create separate folder for each message thinking it would save in the same folder « Output ». Can you kindly advise please? Goal is to save the attachment in the same folder. Thanks again.
Replace target_folder with output_dir
Path(target_folder / "EMAIL_BODY.txt").write_text(str(body))
# Save attachments
for attachment in attachments:
attachment.SaveAsFile(target_folder / str(attachment))
Sven thank you. Coding is indeed fun.
good work, when I print the messages it seems are not in the right order (recent are not showed first). then how I do get the Sender mail address?
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
Hi Sven, I downloaded the Outlook 2016 which I can't update it and can't open it, anyways, I'm using the native mail application from Windows 11, how can I connect to that app instead of Outlook? 🤔
Hi Saul Eduardo Renteria Navarro,
Thanks for watching the video! Regarding your question, I'm not sure about the exact process off the top of my head. I encourage you to search for a solution online. Sorry, that I cannot help here.
Thanks a lot and how about if I want to loop through emails and extract Table contents from the email?
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
Great as usual
Thank you!
💥 I'm a new subscriber.
Welcome aboard! 👋🎉
This was awesome... However, I want to download a specific attachment from the email with a specific subject line, could you please create a tutorial or guide me to such video, that will be a great help.
Thanks in advance 🙂
Thanks! You can adjust the script, e.g. inserting if conditions. Happy Coding!
How do you remove the attachments from the emails after you save them onto your computer ?
Thanks for watching. I am not sure how to implement that
I have a bit of a challenge using the subject as the folder name, i have some email subjects that are not allowed to be used as folder names. how do i handle this
Thanks for watching. Use the updated code: github.com/Sven-Bo/download-messages-attachments-from-outlook/blob/master/retrieve_outlook_data.py
Thank you for vedio . A newbie here . Is there any way to scan outloook emails and search a particular keyword in subject and body ; if found them write that mail subject , body into excel with date . What is important that output excel should have following columns - sender , receipient , subject , body and date
Thanks for watching. That is definitely possible. Unfortunately, I do not have the time to code out a complete example for you.
Hey man great content first of all!!
I am just stuck in a problem where iam extracting data from the .msg file of an email, in which there are replies to an single email and the whole file acts like an email thread with more than one email,
Now when i try to extract the text, everything is fine i get the whole thread's content in a single txt file, but when i want html thats where the problem is, i get only the content of the topmost mail in the whole thread as html from the single .msg file
Any limelight on this would be great.
Thanks!!!
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
Hi Sven this code not working on New Outlook app can you send me any other approach that works on New Outlook app
What do you mean by "New Outlook" and "not working"?
@@CodingIsFunOutlook new version not classic mode . In old classic outlook it is working but if you switch from classic to New outlook it's not working pywin32 client library
Unable to connect to outlook app
How can this be used in the browser version of outlook, I mean those without license to use desktop version of outlook
Thanks for watching. You would need to use the respective API from your E-Mail provider.
attachment.SaveASFile does not work on relative path. I want to specify only the folder name in order to make main.exe later and sent script to other, so once they execute it they will also have there attached messages. Any idea?
Thanks for watching. Why does it not work with relative paths?
@@CodingIsFun Error (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot save the attachment. Path does not exist. Verify the path is correct.', None,
0, -2147024893), None)
This is the error...
@@RisteMojsovski print out the path and then you need to debug it. Perhaps there are special characters in the path. You might also want to watch my pathlib tutorial. Happy debugging!
What should i edit in the code, so i only downloade the attachments?
The following code should do the trick: pastebin.com/eivzEJtW
Thank you very much
Can you use also node JD pls.....
For download messages and attachments
What is node JD?
How to give the mail id in python file, I don't have Outlook application in my system, but still I want to access the outlook
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
How can we download the attachments from outlook items? Which are present in a folder
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
Hello, May I know the same output using IBM Lotus mail data fetch to my computer with the help of win32 library?
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
Could this be done on streamlit where users can do that too?
I believe this will only work on a local machine, as it requires the Outlook application installed on your machine. The solution uses the win32com API to interact with Outlook. Cheers, Sven ✌️
so throughout lifetime will the code enable us to store attachments directly by itself without running the code everyday, if i execute the code once then will it store the attachments everyday by itself
Nope, you would need to modify the code and host it somewhere to run it daily
@@CodingIsFun maybe like a task scheduler, but if i do run it for maybe like every 3hr wouldnt it save the same attachments already saved again along with the new mails attachments ?
😅🙂
@@saketram690 Nope, because if you use the code I provided on GitHub, it will insert a timestamp. Why not simply trying it out :) Happy Coding! Cheers, Sven ✌️
Hi!!
I am applying for a data scientist role and I have the next question.
I have a folder in my outlook with all my applications, and I have another with all the rejections.
I would like to create a bar plot by day with the amount of both folder
Any hint?
I would like to:
(1) Download both folders,
(2) Count the emails that there are for each day
(3) Make a bar plot
The idea is to see the relation between rejection and application and to see that some days I applied for more jobs than others
Thank you!
Pablo
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
Hi....the code's simple and made things easier. Thanks for this code.
is there any way to implement the same in linux. win32 is not compatible in linux.
Thanks for watching. Sorry, but I do not have a solution for linux
@@CodingIsFun any suggestions?
@@druthik7979 Nope, sorry
Hi Sven, amazing tutorial. But I have one task to perform. I made one folder in outlook, and want to download whole month (30 days) emails messages with attachments and make one zipped file through python script. How I do? And one thing is here right now Microsoft basic authentication is not working, how I do.. plz let me know..
Advance thank you
Thanks so much for watching the video and leaving a comment! Your request is definitely noted. However, I get a ton of requests for custom solutions and, as much as I'd love to help everyone out, I just don't have the time in my schedule to develop and test all of them. I hope you can understand. Happy Coding!
I'm getting the below error don't know where is the problem Note(working on Windows workstation ):
retrieve_outlook_data.py
Traceback (most recent call last):
File "C:\Users\alex\Downloads
etrieve_outlook_data.py", line 31, in
target_folder = output_dir / re.sub('[^0-9a-zA-Z]+', '', subject) + "_" + current_time
TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'
Thanks for watching. That was a bug from my side. I have fixed it. Please try it again:
github.com/Sven-Bo/download-messages-attachments-from-outlook
Hey quick question can you tell ..how can we add filters ...by which i mean how can we avoid reading emails with"" RE: or FW: "" in them
Add a condition in your code, e.g.: pastebin.com/SnuCTcL9
@@CodingIsFun Thank you so much for your immediate response
Great Tutorial. However I hav eove 83 messages in my inbox but when I run the script it only downloads 3. And when I rerun it downloads the same 3 messages. Is there a way to fix this please? :(
Thanks for watching and for your question. Hard to tell from a distance why you are facing an error. Sorry that I cannot help.
how can i implement filters in this,? for example i want to download the data belonging to only yesterday 14-6-2022?
everyday i cannot come, and download all the data?
This is how you get the received time: received = (message.ReceivedTime).strftime("%Y_%m_%d")
Hope this gets you started on coding your solution. Happy Coding!
can you do it from a specific email address ?
As shown in the video: You can do it with any email account you linked to Outlook
Great video
Thank you!
Hi, is it possible to extract the outlook mail to excel. Like creating a different columns in excel for sender, subject, content,
Yes, absolutely. Have a look at the openpyxl or xlwings library to manipulate spreadsheets using Python.
it's not a good idea if your emails contained a lot of replies. The excel/csv's cell has its limit. I done one with json and able to migrate it into database
Thanks for this! Please what if I only want the attachments saved. Also I want all attachments from different emails to land inside the same folder destination please :D
Thanks for watching. Feel free to customise the code. If you do not need the subject in a textile, delete the following lines:
# Write body to the text file
Path(target_folder / "EMAIL_BODY.txt").write_text(str(body))
Just try it out. If you are stuck, you can still ask your questions. Thanks, and happy coding!
Thanks, I will give it a shot !
Why am I getting win error 267 the directory name is invalid while running target_folder.mkdir line
@codingisfun
Thanks for watching and for your question. Hard to tell from a distance why you are facing an error. Sorry that I cannot help.
Thank you, this is very helpful. Do you know how i could do this in google colab?
Glad you liked it. Thanks for watching. I am not sure how to do this in google colab, sorry!
How to make sure the script runs automatically using task scheduler
Thanks for watching. Here you are: chatgpt.com/share/4407fcf5-58d5-415f-92a1-fde921687aea
I hope it helps! Cheers, Sven ✌️
how to dowload when there's embedded images in the email? it's not an attached
Thank you for watching the video. Your questions are great, but finding the time to answer them is difficult. Kindly understand that I receive many requests for individual solutions or modifications. That said, you might want to join our Discord server (pythonandvba.com/discord) and post your question there. Thanks for your understanding. Happy Coding!
Hi just wanted to know how to download the attachment (only pdf's) sent to specific mail alias which I am a part of.
What have you tried so far?
@@CodingIsFun followed your video, all attachments sent to me can be downloaded. But now I want to download pdf's which were to sent to mail alias which I am part of.
@@sanjananayak6326 Ok, understood. But what have you tried to solve this? Did you try to adjust the code?
I'm having a problem. The code only searches for emails from a year ago. Why is this happening and how to solve it? Thank you for this amazing tutorial!
Thanks for watching. Hard to tell from a distance. Sorry, that I cannot help.
Do you have the same thing for mac os?
No, sorry!
Hi is it possible to to have the script run and download new emails as they come in? Without downloading all emails in the inbox?
Thanks for watching. That should be possible. One idea would be to use a while loop to check every couple of seconds for new emails.
@@CodingIsFun thanks! Is it possible to share the code ?
@@JL185 Sorry, but I do not have the time to code out an entire example for you. Thanks for your understanding!
I would like raise a question here, the problem with the code is that it only saves the latest email and attached from the entire folder. If you have a folder that has scheduled enabled on it, and receiving emails with same name daily at the same time then this does not work. Big Fail.
That is interesting. In the video, I had 3 emails, and all emails incl. the attachment, have been downloaded. Not sure what you mean by "only saves the latest email". That said, feel free to adjust the code to your needs and liking.
@@CodingIsFun Hi, Thanks for your response.
Lets say I have email scheduled which gives me a report daily at 12 pm noon. So now when I run the code it downloads the latest emails body and attachment from that email folder. Having said that, if there is a previous file in the windows folder it overwrites that file and save a new one. This is the concern.
@@CodingIsFun I was also surprised by this behavior of the code. :P
@@jatinverma5503 Ok, now I understand you. Yet, I would not say 'Big Fail', as the code does exactly what it should. In your case, when saving the attachments, you just want to add an if condition to check whether the file already exists or attach a unique ID to the filename. That said, I do not have the time to code an example for you.
Hi bro I want to log into outlook and leave an email in forwarding is it possible ?? Plz help
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
@@CodingIsFun I understand you perfectly cheer up bro greetings from Morocco
One issue i had right away is that some of our emails have weird and long names. The script had a problem creating a folder name from those email names.
Have you tried to used the updated code from GitHub? Also, feel free to use the code as a starting point and to add additional error handling.
@@CodingIsFun I'm actually using ChatGPT to modify it :)
NotADirectoryError: [WinError 267] The directory name is invalid
Ensure to remove any special characters from the filename before saving it
how can we get outlook access via linux not from windows based lib
Thank you very much for watching the video and your comment. Your requirements are well noted. Yet, I receive many requests for creating individual solutions. As much as I want to help, I simply do not find the time in my daily schedule to develop & test all the different requests. I hope you can understand. Thank you!
Great Module! Appreciate this! i just got stuck where in If the subject has some special characters - it returns error WinError 267 - The directory name is invalid - So half way through the download stopped in the output dir. :)
Thanks! In that case, you could replace any special characters in the subject (Python replace function) before creating the directories.
@@CodingIsFun Could you kindly share the code for replacing the special characters before creating the directories? Thank you!
@@jamiejensen-young2676 Please have a look at the following example: stackoverflow.com/a/23996414
@@CodingIsFun Thank you -this is helpful but now I'm getting a "UnicodeEncodeError" when replacing the special characters... Not sure what to do about this ??
getting this error help anyone?
NotADirectoryError: [WinError 267] The directory name is invalid:
Bevor creating the folders, you might need to replace any special characters.
Hi, it's really interesting and useful codes. But how can we download unread messages attachments? Thank you!😊
Thanks! :) What have you tried so far?
@@CodingIsFun I tried uuid library as
file_uuid = str(uuid.uuid4())
attachment.SaveAsFile(os.getcwd() + '\\' + 'my_attachment_name' + file_uuid)
but too many mails in my box. Python reads them all from beginning to end.
@@cuneytozkurt4867 Try to add an additional if condition:
for message in messages:
if message.UnRead == True:
@@CodingIsFun :) thank you... I tried and worked well
Hi CodingIsFun, How to consolidate excel file from sharepoint using python.
While I'm happy to try and help, it sounds like your question is beyond the scope of the tutorial and would require a custom solution. Unfortunately, I don't have the time to code something specific for every viewer. If you'd like some support and guidance from a community of like-minded people, you might want to check out my Discord server at pythonandvba.com/discord. Good luck with your project. Happy Coding!
Thank a lot
PyWin32 is not platform agnostic. is there a package that is platform agnostic?
I am aware that PyWin32 is not platform agnostic. Hence the hint at the beginning of the video, that it only works on Windows (0:25 min). Unfortunately, I do not know a platform agnostic package that can accomplish the same.
how to differentiate the attachments? Would like to not include the attachments from the texting area, example the signatures or images
It's a good question but such a difficult one to answer because it depends on so many factors. I would image that every signature image has a different name, hence it might be hard to exclude those.
@@CodingIsFun All the images from there would have auto generated naming like image00x.png and ATT0000X.jpg. I was thinking to filter it by the naming, but somehow if the related attachments named with the similar prefix would be filtered out. So, I am stuck now. Anyway, thanks for your great video. I did explore a lot about Python starting from this video.
@@user-dd4nf8zi4c Perhaps using regular expression might help, but I agree that there might be cases where you exclude the wrong file.
@@CodingIsFun faced new issue if the attachment was an outlook item / business card / calendar. How to handle or check the attachment type?
@@user-dd4nf8zi4c You could check the file ending using the pathlib module with an additional if condition.
I have implemented the solution for this at Manulife back in 2019, thank you for the explanation, but this approach would not work in companies, you need to connect to your email directory and some one time activities should be done before jumping into python, I work as data engineer
Great!
@@CodingIsFunoh wow, is this automatic reply?
@@gurue6815 nope 😅
@@CodingIsFun I subscribed
@@gurue6815 welcome aboard 🎉
Does it work to Office 2013?
Just try it out. I don't have office 2013