Automatically Download Email Attachments Using Python. (Python3)

shadow_b

shadowb

Posted on August 8, 2023

Automatically Download Email Attachments Using Python. (Python3)

Hi, We all know that if we get hundreds of emails per day, it's hectic to go through each one and download the attachments. So we can download those attachments using the Python programme. Let's dive into the technical part.

Prerequisite

 pip install tqdm
 pip install python-imap

Enter fullscreen mode Exit fullscreen mode

2) Need to turn on two steps verification on gmail and add app password.Go to Manage you account > security > two step verification >add app password.

3) Go to gmail settings and enable IMAP.

Module Required

import imaplib
import email
import os
from datetime import datetime, timedelta
Enter fullscreen mode Exit fullscreen mode

** Creating folder to download those attachments in it.**

folder_name = today.strftime(f"Mail_Attachments")
if not os.path.exists(folder_name):
    os.makedirs(folder_name, mode=0o777)
folder_path = os.path.abspath(folder_name)
Enter fullscreen mode Exit fullscreen mode
 user = "yourmailid@gmail.com"
    password = "copy_pass_from_app_password"
    imap_url = 'imap.gmail.com'
    my_mail = imaplib.IMAP4_SSL(imap_url)
    my_mail.login(user, password)
    my_mail.select('Inbox')
Enter fullscreen mode Exit fullscreen mode

Now we need to specify from which date we need to fetch and download the attachments.
Let's suppose we are taking yesterday(From Yesterday to Today)


    today = datetime.now()
    yesterday = today - timedelta(days=1)
    yesterday_date_string = yesterday.strftime("%Y-%m-%d")

    search_query = f'(X-GM-RAW "has:attachment after: 
    {yesterday_date_string}")'
    result, data = my_mail.search(None, search_query)
    email_ids = data[0].split()
Enter fullscreen mode Exit fullscreen mode

Using for loop we are iterating through all the mails retrieved and checking the attachments if yes we are downloading it below code will show how we are doing it.
Using tqdm to show download progress bar to user (optional).

 for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            if filename:
                filepath = os.path.join(folder_path,filename)
                with open(filepath, 'wb') as f:
                    f.write(part.get_payload(decode=True))

    my_mail.logout()
Enter fullscreen mode Exit fullscreen mode

I hope you guys got it if you have any questions please let me know in comment section.

💖 💪 🙅 🚩
shadow_b
shadowb

Posted on August 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related