Search code examples
pythonstringsmtplibmultilinestring

Python: Use Variable in mulit-line string


i have two variables:

subject = 'this is the subject'
body = 'this is the content'

For sending this per e-mail with smtplib i have my message variable as an multi line string. But the .format() method doesn't work. Has anybody an idea to solve this?

The message String:

    message = """\
    Subject: (variable subject)


    (variable content)"""

Solution

  • You can use an f string for simplicity:

    message = f"""
        Subject: {subject}
    
    
        {body}"""
    

    Heres the right way to use format():

    message = """
    subject = {}
    
    
    {}
    """.format(subject, body)
    

    to use format, place {} where your variables need to be added and then declare .format() with a sequential list of the variables you want those {}'s to be replaced with