0

I want to automatically download the latest email attachment from gmail based on subject. i have daily data with same subject in email, and i want automatically download it everyday, can u guys help complete my code?

Here's my code :

typ, msgs = mail.search(None, '(FROM "Jordan Chai" SUBJECT "TEST")')
msgs = msgs[0].split()

for num in msgs:    
    resp, data = mail.fetch(num, "(RFC822)")

    email_body = data[0][1]
    m = email.message_from_bytes(email_body)

    # downloading attachments
    if m.get_content_maintype() != 'multipart':
        continue

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

        filename = part.get_filename()
        if filename is not None:
            sv_path = os.path.join(svdir, filename)
            if not os.path.isfile(sv_path):
                fp = open(sv_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

                subject = str(m).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
                print('Downloaded "{file}" successfully to "{path}".'.format(file=filename, path=sv_path))

So, if there are email with subject "TEST", it will download the latest email with subject TEST and i want this script automatically works everyday, can u guys help?

  • So, assuming you’re not moving messages back and forth, the message with the largest ID will the newest. So, just take the largest one from your SEARCH result. – Max May 11 '20 at 14:10
  • i just want get the email from todat, because my data is daily data and i want to download it daily, can i do that? @Max – Jordan Chai May 12 '20 at 05:16
  • You have a list of ids. The largest one is the newest message. Maybe max(list) will help you? You may want to learn a little bit more python so you can do some more tasks in it before getting too far into tackling a complex problem like fetching emails in IMAP. – Max May 12 '20 at 13:58

0 Answers0