我使用emails
库发送邮件,但我还需要将其保存为.msg
文件。我已经完成了一些研究,并且还阅读了msg格式规范,偶然发现了this SO answer,它显示了如何将邮件发送到C#
中的文件系统,我想知道它是否可以在Python中作为好。
答案 0 :(得分:4)
这是可能的,也很容易。让我们假设msg
是一个包含所有标题和内容的先前编写的消息,并且您希望将其写入文件对象out
。你只需要:
gen = email.generator.Generator(out) # create a generator
gen.flatten(msg) # write the message to the file object
完整示例:
import email
# create a simple message
msg = email.mime.text.MIMEText('''This is a simple message.
And a very simple one.''')
msg['Subject'] = 'Simple message'
msg['From'] = 'sender@sending.domain'
msg['To'] = 'rcpt@receiver.domain'
# open a file and save mail to it
with open('filename.elm', 'w') as out:
gen = email.generator.Generator(out)
gen.flatten(msg)
filename.elm的内容是:
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Simple message
From: sender@sending.domain
To: rcpt@receiver.domain
This is a simple message.
And a very simple one.
答案 1 :(得分:1)
是的,有可能。 有用于这些目的的模块,它称为MSG PY。 例如:
from independentsoft.msg import Message
from independentsoft.msg import Recipient
from independentsoft.msg import ObjectType
from independentsoft.msg import DisplayType
from independentsoft.msg import RecipientType
from independentsoft.msg import MessageFlag
from independentsoft.msg import StoreSupportMask
message = Message()
recipient1 = Recipient()
recipient1.address_type = "SMTP"
recipient1.display_type = DisplayType.MAIL_USER
recipient1.object_type = ObjectType.MAIL_USER
recipient1.display_name = "John Smith"
recipient1.email_address = "John@domain.com"
recipient1.recipient_type = RecipientType.TO
recipient2 = Recipient()
recipient2.address_type = "SMTP"
recipient2.display_type = DisplayType.MAIL_USER
recipient2.object_type = ObjectType.MAIL_USER
recipient2.display_name = "Mary Smith"
recipient2.email_address = "Mary@domain.com"
recipient2.recipient_type = RecipientType.CC
message.subject = "Test"
message.body = "Body text"
message.display_to = "John Smith"
message.display_cc = "Mary Smith"
message.recipients.append(recipient1)
message.recipients.append(recipient2)
message.message_flags.append(MessageFlag.UNSENT)
message.store_support_masks.append(StoreSupportMask.CREATE)
message.save("e:\\message.msg")
答案 2 :(得分:0)
它在Python中是可行的,我尝试了以下代码,它将Outlook文件中的.msg保存在文件夹中。 注意:确保outlook具有对目标文件夹的写访问权限,默认情况下,目标文件夹是Python脚本的位置
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.items
for msg in messages:
name = msg.subject
name = str(name)
name = name + ".msg"
msg.saveas(name)
答案 3 :(得分:0)
我认为这个问题的答案(但问题不是很清楚,部分内容在评论中)是:
import email
from email.message import EmailMessage
如果 msg
是使用 msg = EmailMessage()
创建并填充了适当的调用(参见 https://docs.python.org/3/library/email.examples.html),那么 msg
可以使用
with open('mymessage.msg', 'wb') as f:
f.write(bytes(msg))
并且可以使用以下方法恢复该文件:
with open('mymessage.msg', 'rb') as fp:
msg = email.message_from_binary_file(fp)