1

I want to retrieve new mails using a shell script and if the mail I just retrieved has attachments, these attachments should be saved to a folder. Before the next mail is retrieved, the attachments should be processed individually, e.g. the name should be checked and the file should be moved etc.

I know how to retrieve mails from the command line and save the attachments (with mutt), but then all mail attachments are saved. So I cannot check and process the attachments for each mail immediately after receiving it.

I would be glad about tips.

cu Andy

0

I came up with a script below. Please note that I'm not a programmer. But I believe this could be a good start for You.

Run it for each message like this ./script FILENAME

There are couple of things to finish:

  • duplicate filenames,
  • missing filenames,
  • Better handling of multipart/related.
#!/usr/bin/env python3
import os
import sys
import email

fp = open(sys.argv[1],"r")
msg = email.message_from_file(fp)
fp.close()

content_types_to_skip=[
  'text/plain',
  'text/html',
  'multipart/mixed',
  'multipart/alternative',
  'multipart/related'
]
attach_dir='/tmp/attachments/'
if not os.path.exists(attach_dir):
  os.mkdir(attach_dir)

# get text/plain only
if msg.is_multipart():
  for part in msg.walk():
    ctype = part.get_content_type()

    if ctype not in content_types_to_skip:
      attachment = part.get_payload(decode=True)
      name = str(part.get_filename())
      fp = open(attach_dir + name,"wb")
      fp.write(attachment)
      fp.close()
| improve this answer | |
  • Cool start. Thank you, Jakub! – Ripley Mar 30 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.