'Using HTML templates to send emails in python

I'm trying to write a separate mail service, which is decoupled with our Flask application. I'm looking for a way to send welcome emails when users first log into our Flask application. I'm using Celery and RabbitMQ to do it asynchronously.

Here is my email function:

sen = '[email protected]'
pwd = 'my_password'

@celery.task
def send_email(nickname, email):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = 'my_sub'
    msg['From'] = sen
    msg['To'] = email

    html = <b>test_body</b>

    part1 = MIMEText(html, 'html')
    msg.attach(part1)

    server = smtplib.SMTP("smtp.gmail.com", 587) 
    server.ehlo()
    server.starttls()
    server.login(sen, pwd)
    server.sendmail(sen, [email], msg.as_string())
    server.close()

Initially I was using Flask's render_template to get the HTML body and subject. But I don't want to use the Flask extension (I have my reasons). So my questions are:

  1. How can I use email templates so that the subject and body fields can be configured easily?

  2. How can I put the default email sender and password in a config file/email template (might be related to q1)?

  3. It seems to be that I have a lot of code to send a simple email. Can you suggest some optimization techniques (omitting steps)?



Solution 1:[1]

I've wrritten a simple module(mail.py) to send emails using templates(HTML/TEXT). Hope that helps!

https://github.com/ludmal/pylib

Solution 2:[2]

It may be simpler to use an external service.

A service (e.g. Mailchimp) is simple to integrate. You can design the template in their layer, and trigger emails by sending merge data from your app to the service API. Functionally it's a lot like rendering a template locally and mailing it out via SMTP, but they have sophisticated tools for adapting message format to devices, tracking bounces, improving deliverability, reporting etc.

Services like this often have a free tier for up to 1000's of emails per month.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ludmal
Solution 2 Chris Johnson