使用Python保存到.msg文件,或者将邮件发送到文件系统 [英] Saving to .msg file in Python, or alternatively, sending mail to the file system

查看:273
本文介绍了使用Python保存到.msg文件,或者将邮件发送到文件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用电子邮件库发送邮件,但我还需要将其另存为 .msg 文件。我进行了一些研究,还阅读了msg格式规范,偶然发现了此SO答案,其中显示了如何将邮件发送到 C#中的文件系统,我想知道是否也可以在Python中使用。

I'm using the emails library to send mail, but I also need to save it as .msg file. I've done some research and also read the msg format specification and stumbled upon this SO answer that shows how to send mail to the file system in C# and I was wondering if it was possible in Python as well.

推荐答案

这是可能且容易的。假设 msg 是包含所有标头和内容的先前编写的消息,并且您想将其写入文件对象 out 。您只需要:

It is possible and easy. Let's assume that msg is a previously composed message with all headers and content, and that you want to write it to the file object out. You just need:

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的内容为:

The content of filename.elm is:

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.

这篇关于使用Python保存到.msg文件,或者将邮件发送到文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆