8

So I have this as part of a mail sending script:

try:
    content = ("""From: Fromname <fromemail>
    To: Toname <toemail>
    MIME-Version: 1.0
    Content-type: text/html
    Subject: test

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

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

...

    mail.sendmail('from', 'to', content)

And I'd like to use different subjects each time (let's say it's the function argument).

I know there are several ways to do this.

However, I am also using ProbLog for some of my other scripts (a probabilistic programming language based in Prolog syntax). As far as I know, the only way to use ProbLog in Python is through strings, and if the string is broke in several parts; example = ("""string""", variable, """string2"""), as well as in the email example above, there's no way I can make it work.

I actually have a few more scripts where using variables in multiline strings could be useful, but you get the idea.

Is there any way to make this work? Thanks in advance!

dreftymac
  • 31,404
  • 26
  • 119
  • 182
  • 2
    I'm confused what you're trying to do. – erip Mar 09 '16 at 21:31
  • 3
    You appear to want a multi-line `String`, not a multi-line comment. Using a variable in a comment wouldn't make any sense - comments aren't executed. – Elliott Frisch Mar 09 '16 at 21:33
  • Python doesn't _have_ multi-line comments. Triple-quoted strings are **not** comments. – PM 2Ring Mar 09 '16 at 21:47
  • That's right. Sorry. Multiline strings. I'm new into python. I just didn't thought about it. –  Mar 09 '16 at 21:48
  • This question was incorrectly marked as a duplicate of http://stackoverflow.com/questions/517355 ... this question is not a duplicate because the other question does not refer to using multi-line strings – dreftymac Mar 09 '16 at 22:13

1 Answers1

16

Using the .format method:

content = """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>
"""
mail.sendmail('from', 'to', content.format(toname="Peter", toemail="p@tr", subject="Hi"))

Once that last line gets too long, you can instead create a dictionary and unpack it:

peter_mail = {
    "toname": "Peter",
    "toemail": "p@tr",
    "subject": "Hi",
}
mail.sendmail('from', 'to', content.format(**peter_mail))

As of Python 3.6, you can also use multi-line f-strings:

toname = "Peter"
toemail = "p@tr"
subject = "Hi"
content = f"""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>
"""
L3viathan
  • 26,748
  • 2
  • 58
  • 81