0

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?

Community
  • 1
  • 1
  • What is `mail.sendmail`? You shouldn't have to generate the headers like `To:`, and `Subject:` manually. You leave yourself open to header injection. – Alasdair Mar 09 '16 at 23:33
  • Sorry; mail = smtplib.SMTP('smtp.gmail.com', 587) –  Mar 09 '16 at 23:49
  • I am using this just on my computer for now. It is the most suitable solution at the moment. But thanks! –  Mar 09 '16 at 23:50

1 Answers1

1

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!

  • I wrote that answer, but then deleted it because I thought that you might be better using the [emai](https://docs.python.org/2/library/email-examples.html) package instead. Glad it helped. I still think it would be a good idea to take a look at the email package, because it should allow you to separate your message body from the headers, rather than having them all in one string. – Alasdair Mar 10 '16 at 09:46
  • Thanks! I've tried email package before and for some reason I couldn't make it work haha. I know it's better but as at time of posting my previous question I was looking for a solution that'd work for other not-email scripts with multiline strings, I actually was curious about what was I doing wrong this time. –  Mar 11 '16 at 12:44