Search code examples
pythonhtmlpython-3.xstring-formatting

How to modify HTML code inside Python code?


I'm working with Django in order to create a website. I have an function which send e-mail message that is called with a button in the HTML file. I would like to insert a python variable to the HTML code inside of the python function:

import smtplib, ssl, getpass

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def mailfunctionejex(receiver_email, subject, message, passwordtest):
    port = 465
    smtp_server = 'smtp.gmail.com'
    sender_email = 'senderg@gmail.com'
    failcounter = 0

    #MIME parameters

    mailmessage = MIMEMultipart()
    mailmessage['Subject'] = subject
    mailmessage['From'] = sender_email
    mailmessage['To'] = receiver_email
    mailmessage['Bcc'] = receiver_email

    #Message content

    html = '''\
        Good morning, the user {sender_email} has send you a message: \n

        {message} #I would to insert in {} the variable sender_email and             #message 

        '''

    #Conversions
    htmlpart = MIMEText(html, 'html')

    mailmessage.attach(htmlpart)


.
.
.

Solution

  • This is just a string like any other one, so this should do (I added an f before the string to tell Python it's a format string):

    html = f'''\
            Good morning, the user {sender_email} has send you a message: \n
    
            {message}  
    
            '''
    

    If this doesn't work, you can go the old way:

    html = 'Good morning, the user'+ sender_email+ 'has send you a message: \n'
    
            +message