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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With