Motivation

Sending emails may seem to be a simple task. But there is some complicated stuff to consider:

  1. An email should be sent in a parallel thread, so it does not pause the whole project
  2. An email should be beautiful and support different formats — Text and HTML.
  3. Security issues. Does your email server require SSL? Sending from Gmail.

Image for post

© You’ve Got Mail


Simple Email send

Sending emails is no rocket science in Python. As usual, batteries are already included, so we need to insert them:

import smtplib, ssl
from email.mime.text 
import MIMETextfrom email.mime.multipart 
import MIMEMultipart

Now, as batteries are in, we only need to press the red button:

server = smtplib.SMTP(email_smtp_server, email_port))
server.login(email_login, email_password)
server.sendmail(email_from, email_to, message.as_string())

Ooops, what are all these variables? Sure, we need to supply our code with the email properties, subject, and email text.

Email properties are the email_smtp_server, which is a simple string, and the email_port, which is an integer.

All the rest goes to the message variable, which is something more complex:

body = "<html>"
body += "<h2>Guten Tag!</h2><br><br>"
body += "<b>This is an automatic email.</b><br>"
body += "Please do not reply.<br><br>"
body += "Best regards,<br>"
body += "Your server.<br>"
body += '<img src="http://realitycheckbbs.org/images/fido.jpg">'
body += "</html>"

#email #python #threads #gmail #programming

Multithreading for Emails in Python
8.40 GEEK