如何将邮件转换为eml?

问题描述 投票:0回答:2

将邮件转换为 EML?

我有一台服务器,我想将其邮件转换为 EML 进行备份

如何实现这一点?

尝试了以下方法;

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= '[email protected]')
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()

上面的方法可以工作,但是打开文件时没有得到输出

也尝试过这个:

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)

导致错误:AttributeError: “MailMessage”对象没有属性“policy”

请帮忙!

python imap mailmessage eml imap-tools
2个回答
1
投票

你必须学Python,还有一些算法书。

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

您似乎试图复制/粘贴而不是编程。

我并不是想作恶。


0
投票

Ваша идея верная, но вы как-то странно сохраняете файл.
Сохранить тело письма можно так:

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)

Это работает в моём коде.

© www.soinside.com 2019 - 2024. All rights reserved.