0

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 = '[email protected]'
    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)


.
.
.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

If f-strings aren't an option, I'd suggest using str.format before going for str concatenation, e.g. 'Good morning, the user {} has send you a message:\n{}'.format(sender_email, message) or the f-string-like 'Good morning, the user {sender_email} has send you a message:\n{message}'.format_map(locals()). String concatenation involves many temporary strings (it's a Schlemiel the Painter's Algorithm), requires all inputs to already be str (where str.format will stringify implicitly), and is uglier (subjective opinion).
I'm glad it did !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.