0

Convert mails to EML?

I have a server of which I want to convert mails to EML to backup

How to accomplish this?

Tried the following;

import imaplib
import getpass
import argparse

argparser = argparse.ArgumentParser(description="Dump a IMAP folder into .eml files")
argparser.add_argument('-s', dest='host', help="IMAP host, like imap.gmail.com", default= 'mail..nl')
argparser.add_argument('-u', dest='username', help="IMAP username", default= 'e@.nl')
argparser.add_argument('-r', dest='remote_folder', help="Remote folder to download", default='INBOX.html')
argparser.add_argument('-l', dest='local_folder', help="Local folder where to save .eml files", default='.')
args = argparser.parse_args()

gmail = imaplib.IMAP4_SSL(args.host)
gmail.login(args.username, password1)
gmail.select(args.remote_folder)
typ, data = gmail.search(None,'ALL')
for num in data[0].split():
    typ, data = gmail.fetch(num, '(RFC822)')
    f = open('%sand%s  .eml' %(args.local_folder, num), 'w')
    print(data[0][1], file=f)
    f.close()
gmail.close()
gmail.logout()

The above is working however not getting an output when opening the file

Also tried this:

import os
cwd = os.getcwd()
outfile_name = os.path.join(cwd, 'message.eml')

class Gen_Emails(object):    
    def SaveToFile(self,msg):
        with open(outfile_name, 'w') as outfile:
            gen = generator.Generator(outfile)
            gen.flatten(msg)

with MailBox('mail.yourubl.nl').login('login.nl', 'pwd', initial_folder='INBOX') as mailbox:
    for msg in mailbox.fetch():
        SaveToFile(msg)

Leading to error:AttributeError: 'MailMessage' object has no attribute 'policy'

Please help!

Max
  • 493
  • 2
  • 9
  • 1
    In your first script, you aren't adding a '/' to the path. If the user specified "/home/user/Documents" for local_folder, then the messages would be stored as files called `Documentsand13 .eml` in the users home, NOT in the Documents folder. You probably want to remove the spaces in there, as well. – Tim Roberts Jun 20 '21 at 21:22

2 Answers2

1

You must learn python, and some algorithmization book.

https://github.com/ikvk/imap_tools/blob/master/examples/email_to_file.py

It seem that you trying to copy/paste instead of programming.

I am not trying to be evil.

Vladimir
  • 6,162
  • 2
  • 32
  • 36
-1

Your idea is correct, but you are saving the file in a strange way. You can save the body of the letter like this:

typ, data = gmail.fetch(num, '(RFC822)')
email_message = data[0][1]
filename = f'unread_message_{num.decode()}.eml'
with open(filename, 'wb') as f:
    f.write(email_message)

It works in my code.

TitanRain
  • 99
  • 1
  • 4