0

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)


user78910
  • 349
  • 2
  • 12
Florian Seliger
  • 421
  • 4
  • 16
  • By timed out, I am assuming that the time it was trying to connect to the server to download the emails but went over the estimated or suggested time before shutting off. This program didnt have this issue earlier and the program wasnt modified in any way? – Redgar Tech Jun 02 '20 at 16:07
  • Exactly. It wasn't modified and it was working (albeit very slowly). – Florian Seliger Jun 03 '20 at 14:30
  • It is probably a connection time out or a changed connection to the server. Did you change the network you run this program on? Is there a minimum of Megabits you need? 100, 200, 300, etc. – Redgar Tech Jun 03 '20 at 20:30
  • no, I didn't change anything – Florian Seliger Jun 04 '20 at 10:47

0 Answers0