Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 877
user2216194 Avatar asked Nov 23 '22 12:11

user2216194


1 Answers

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

https://github.com/ludmal/pylib

like image 197
ludmal Avatar answered Nov 26 '22 00:11

ludmal