使用Python的email.generator包创建电子邮件草稿

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

我目前正在使用此代码通过Python生成电子邮件:

from email import generator
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def Create_Email():
    msg            = MIMEMultipart('alternative')
    msg['Subject'] = 'My Subject'
    msg['To']      = '[email protected]'

    html = """\
    <html>
        <head></head>
        <body>hello world</body>
    </html>"""

    part = MIMEText(html, 'html')
    msg.attach(part)

    outfile_name = r'C:\Downloads\email_sample.eml'
    with open(outfile_name, 'w') as outfile:
        gen = generator.Generator(outfile)
        gen.flatten(msg)

Create_Email()

但是当我使用Outlook打开文件时,它显示为已经发送电子邮件:

[enter image description here

如何更改此设置,以便将保存的文件视为草稿,我仍然可以对其进行编辑然后发送?像这样:

[enter image description here

如果email.generator无法做到这一点,我很乐意使用替代软件包。

python python-3.x email
2个回答
0
投票
我创建了一封短邮件,并将其保存到我的草稿文件夹中。但是,执行代码时,您将需要打开Outlook,否则它将要求您提供Outlook配置文件。

与您使用的模块不同。

import win32com.client as win32 def create_mail(text, subject, recipient, send=True): outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = recipient mail.Subject = subject mail.HtmlBody = text if send: mail.send() else: mail.save() create_mail("Hello World!", "Test-Mail", "[email protected]", send=False)


0
投票
[我想避免在创建电子邮件/草稿时依赖于Outlook。

我发现的解决方案最终很简单;只需添加此标题:

msg.add_header('X-Unsent', '1')

它将电子邮件标记为

未发送,即草稿

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