在Python中使用smtplib在多行字符串中使用变量的正确方法是什么?

时间:2016-03-09 23:07:48

标签: python smtplib

我刚刚在几小时前发布了这个问题:Is there any way to use variables in multiline string in Python?

现在我正在使用评论中建议的以下代码:

from string import Template
import textwrap

...

try:
    subject_mail = {
                'subject': 'Test'
                }
    content = Template("""From: fromname <fromemail>
        To: toname <toemail>
        MIME-Version: 1.0
        Content-type: text/html
        Subject: ${subject}

        This is an e-mail message to be sent in HTML format

        <b>This is HTML message.</b>
        <h1>This is headline.</h1>
        """)
    result = content.safe_substitute(subject_mail)
    result = textwrap.dedent(result)

...

print(result)
mail.sendmail('fromemail', 'toemail', result)

奇怪的是,如果我不替换任何东西(如果我在字符串中写入主题),一切正常。 如果我替换上面的主题,它打印出来确定。但是,在我的电子邮件(gmail)中,我得到了这个:

from:   fromname <fromemail> To: toname MIME-Version: 1.0 Content-type: text/html Subject: Test! <toemail>
to:
Cco: toemail
Subject:

没有主题。我不明白。我错过了什么?

1 个答案:

答案 0 :(得分:1)

有人发布了立即删除的解决方案:

content = Template("""\
    From: fromname <fromemail>
    To: toname <toemail>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: ${subject}

    This is an e-mail message to be sent in HTML format

    <b>This is HTML message.</b>
    <h1>This is headline.</h1>
    """)

右缩进。 现在工作正常!

相关问题