问题
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!
回答1:
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))
来源:https://stackoverflow.com/questions/35903017/is-there-any-way-to-use-variables-in-multiline-string-in-python