Search code examples
pythonflaskflask-wtformssmtplib

How to format an email which contains form data using HTML?


I'm trying to format an email using HTML, which gets sent to me whenever someone fills up a form along with the form data e.g. {{ name }}. Currently, I managed to pass the form data via email using an "f" string. I don't know how to make field titles (e.g. Client name:, Email:) bold so that they don't blend with the form data.

        MY_EMAIL = os.environ.get('MY_EMAIL')
        MY_EMAIL_PASSWORD = os.environ.get('MY_EMAIL_PASSWORD')
        
        message = EmailMessage()
        message['Subject'] = "New form submitted"
        message['From'] = MY_EMAIL
        message['To'] = "an_email@hotmail.com"
        message.set_content(f" Client name: {client_name}\n\n Email: {client_email}")
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(MY_EMAIL, MY_EMAIL_PASSWORD)
            smtp.send_message(message)

Current example of the email message:

Client name: Jack

Email: blackjack@hotmail.com

Desired result ("Client name", "Email to be in bold"):

Client name: Jack

Email: blackjack@hotmail.com


Solution

  • The answer is in email.mime.text module. This module provides a function, which allows to render HTML code in your "f" string. This bit had to be added:

                message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"
                message = MIMEText(message, "html")
    

    Here is the full code:

    from email.mime.text import MIMEText
    
            MY_EMAIL = os.environ.get('MY_EMAIL')
            MY_EMAIL_PASSWORD = os.environ.get('MY_EMAIL_PASSWORD')
            
            message = EmailMessage()
            message = f"<b>Client name:</b> {client_name}<br></br> <b>Email:</b> {client_email}"
            message = MIMEText(message, "html")
            message['Subject'] = "New form submitted"
            message['From'] = MY_EMAIL
            message['To'] = "an_email@hotmail.com"
            
            with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
                smtp.login(MY_EMAIL, MY_EMAIL_PASSWORD)
                smtp.send_message(msg_for_me)