在Python中保存到.msg文件,或者将邮件发送到文件系统

2024-05-17 16:08:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用emails库发送邮件,但还需要将其保存为.msg文件。我做了一些研究,也阅读了msg格式规范,偶然发现了this SO answer,它展示了如何在C#中向文件系统发送邮件,我想知道在Python中是否也可以。


Tags: 文件answer规范so格式邮件msgthis
1条回答
网友
1楼 · 发布于 2024-05-17 16:08:04

这是可能和容易的。假设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.
网友
2楼 · 发布于 2024-05-17 16:08:04

这在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楼 · 发布于 2024-05-17 16:08:04

是的,这是可能的。 有用于这些目的的模块,称为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")

相关问题 更多 >