是否将邮件转换为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= '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()
以上是工作的,但在打开文件时没有得到输出
也尝试过这个:
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和一些算法书。
https://github.com/ikvk/imap_tools/blob/master/examples/email_to_file.py
你似乎在试图复制/粘贴而不是编程。
我不想做邪恶的人。
您的想法是正确的,但您以一种奇怪的方式保存文件。你可以这样保存信件的正文:
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)
它在我的代码中有效。