Create dynamic HTML email content using Python

I have a python dictionary that I would like to send an email in the form of a table with two columns, where I have a Header and two column headers, and a couple of keys, the value of the dictionary, filled in rows.

<tr>
<th colspan="2">
<h3><br>title</h3>
</th> </tr>
<th> Column 1 </th>
<th> Column 2 </th>
"Thn dynamic amount of <tr><td>%column1data%</td><td>%column2data%</td></tr>

Column1 and column2 data are key pairs, values ​​from the corresponding dictionary.

Is there a way to do this in a simple way? This is a sent email via cronjob, once a day after filling in the data.

Thanks to everyone. PS I do not know anything about markdowns: /

PSS I am using Python 2.7

+4
source share
2 answers

Basic example: (with template)

#!/usr/bin/env python

from smtplib import SMTP              # sending email
from email.mime.text import MIMEText  # constructing messages

from jinja2 import Environment        # Jinja2 templating

TEMPLATE = """
<html>
<head>
<title>{{ title }}</title>
</head>
<body>

Hello World!.

</body>
</html>
"""  # Our HTML Template

# Create a text/html message from a rendered template
msg = MIMEText(
    Environment().from_string(TEMPLATE).render(
        title='Hello World!'
    ), "html"
)

subject = "Subject Line"
sender= "root@localhost"
recipient = "root@localhost"

msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient

# Send the message via our own local SMTP server.
s = SMTP('localhost')
s.sendmail(sender, [recipient], msg.as_string())
s.quit()

Relevant documentation:

NB: , MTA .

. :. ; . Examples

:. (-) , :

, , requests - SMTP

+4

, ( ), Mandrill. Mailchimp, "" , . 10 000 , , , WYSIWYG, API- python.

, :

  • WYSIWYG Mailchimp. "merge vars".

  • Mailchimp Mandrill

  • cronjob python script Mandrill, .

python Mandrill Python:

import mandrill
mandrill_client = mandrill.Mandrill(mandrill_api_key)
message = {
    'from_email': 'gandolf@email.com',
    'from_name': 'Gandolf',
    'subject': 'Hello World',
    'to': [
        {
            'email': 'recipient@email.com',
            'name': 'recipient_name',
            'type': 'to'
        }
    ],
    "merge_vars": [
        {
            "rcpt": "recipient.email@example.com",
            "vars": [
                {
                    "name": "merge1",
                    "content": "merge1 content"
                }
            ]
        }
    ]
}
result = mandrill_client.messages.send_template(template_name="Your Template", message=message)
+2

All Articles