I am trying to download Email attachments in Python.
I am mainly drawing on this:
Downloading multiple attachments using imaplib
I want to run the code once per week to download all new attachments (I delete old emails).
It was working (although very slowly) for a while, but since 3-4 days I always get a TimeoutError: [Errno 60] Operation timed out
Any ideas on how to deal with this error?
I am running the code in a Jupiter notebook on Safari or Chrome (Mac).
This is my code:
import email
import imaplib
import os
server = 'outlook.office.com'
user = 'florian.xcvh@jiko.ch'
password = 'XXXXYYY'
outputdir = '/Users/florian/Documents/weekly_data'
subject = 'Interesting stuff' #subject line of the emails you want to download attachments from
# Connect to an IMAP server
def connect(server, user, password):
m = imaplib.IMAP4_SSL(server)
m.login(user, password)
m.select()
return m
# Download all attachment files for a given email
def downloaAttachmentsInEmail(m, emailid, outputdir):
resp, data = m.fetch(emailid, "(BODY.PEEK[])")
email_body = data[0][1]
mail = email.message_from_bytes(email_body)
if mail.get_content_maintype() != 'multipart':
return
for part in mail.walk():
if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
open(outputdir + '/' + part.get_filename(), 'wb').write(part.get_payload(decode=True))
#download attachments from all emails with a specified subject line
def downloadAttachments(subject):
m = connect(server, user, password)
m.select("Inbox")
typ, msgs = m.search(None, '(SUBJECT "' + subject + '")')
msgs = msgs[0].split()
for emailid in msgs:
downloaAttachmentsInEmail(m, emailid, outputdir)
downloadAttachments(subject)