Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a dynamic content into html for sending mail in Python

I am sending mail with html content using 'smtplib' in python , I want to add dynamic content to that html.

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

message = MIMEMultipart("alternative")
message["Subject"] = "Error Notification"
message["From"] = sender
message["To"] = sender

# Create the plain-text and HTML version of your message
html = """\
    <html>
      <body>
        <p>Hi,<br>
           <span>Something went wrong !</span><br>
        </p>
      </body>
    </html>
    """
part1 = MIMEText(html, "html")

# Add HTML/plain-text parts to MIMEMultipart message
message.attach(part1)
try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "Successfully sent email"
except smtplib.SMTPException:
    print "Error: unable to send email"

Along with the above html I need to include some of my dynamic contents inside the body tag

like image 767
Aswathy MA Avatar asked Oct 23 '25 06:10

Aswathy MA


1 Answers

Since this is Python you can do really awesome things with strings. Just name certain areas of the html with special names and then use the replace method to replace them with whatever value you want.

html = """\
    <html>
      <body>
        <p>Hi, $(name)<br>
           <span> $(error) </span><br>
        </p>
      </body>
    </html>
"""

html = html.replace("$(name)", "John")
html = html.replace("$(error)", "Something went wrong!")

print(html)
like image 188
babaliaris Avatar answered Oct 24 '25 21:10

babaliaris