python send email with html template

Solutions on MaxInterview for python send email with html template by the best coders in the world

showing results for - "python send email with html template"
Enrico
28 Jan 2018
1# import the necessary components first
2import smtplib
3from email.mime.text import MIMEText
4from email.mime.multipart import MIMEMultipart
5port = 2525
6smtp_server = "smtp.mailtrap.io"
7login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
8password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap
9sender_email = "mailtrap@example.com"
10receiver_email = "new@example.com"
11message = MIMEMultipart("alternative")
12message["Subject"] = "multipart test"
13message["From"] = sender_email
14message["To"] = receiver_email
15# write the plain text part
16text = """\
17Hi,
18Check out the new post on the Mailtrap blog:
19SMTP Server for Testing: Cloud-based or Local?
20/blog/2018/09/27/cloud-or-local-smtp-server/
21Feel free to let us know what content would be useful for you!"""
22# write the HTML part
23html = """\
24<html>
25  <body>
26    <p>Hi,<br>
27       Check out the new post on the Mailtrap blog:</p>
28    <p><a href="/blog/2018/09/27/cloud-or-local-smtp-server">SMTP Server for Testing: Cloud-based or Local?</a></p>
29    <p> Feel free to <strong>let us</strong> know what content would be useful for you!</p>
30  </body>
31</html>
32"""
33# convert both parts to MIMEText objects and add them to the MIMEMultipart message
34part1 = MIMEText(text, "plain")
35part2 = MIMEText(html, "html")
36message.attach(part1)
37message.attach(part2)
38# send your email
39with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
40    server.login(login, password)
41    server.sendmail(
42        sender_email, receiver_email, message.as_string()
43    )
44print('Sent')