user5835566
user5835566

Reputation:

What is the right way to use variables in multiline strings with smtplib in Python?

I just posted this question a few hours ago: Is there any way to use variables in multiline string in Python?

Right now I'm using the following code suggested in a comment:

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)

The weird thing is that everything works fine if I don't substitute anything (if I write the subject inside the string). If I substitute the subject as above, it prints out ok. However, in my email (gmail) I get this:

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

No subject. I don't get it. I am missing something?

Upvotes: 0

Views: 206

Answers (1)

user5835566
user5835566

Reputation:

Someone posted this solution that was immediately deleted:

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>
    """)

Right indentation. Now works fine!

Upvotes: 1

Related Questions