[[python_wiki:send_email]]

Send Email

General Information

Sending HTML Supported emails with Python.

Checklist

  • Multiple imports

Usage

Instructions here.

Execution code here

The Code

send-email.py
#=======================
# Import Modules
#=======================
 
# smtplib: send email
import smtplib
 
# MIME: support for html messages
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
 
 
#=======================
# CUSTOMIZE HERE
#=======================
# Send email to/from
email_to="system_admins@example.com"
email_from="root@system01.example.com"
 
 
#=====================================
# Functions; Main starts after
#=====================================
# Function: Send email
def send_email(send_from, send_to, subject, message):
 
  #--DEBUG--#
  #print("\nSend from: " + send_from)
  #print("Send to: " + send_to)
  #print("Message: " + message)
 
  # Create HTML Supported MIME Type Message
  message_container = MIMEMultipart('alternative')
  message_container['Subject'] = subject
  message_container['From'] = send_from
  message_container['To'] = send_to
 
  # Add HTML formatted Message
  message_html = MIMEText(message, 'html')
  message_container.attach(message_html)
 
  # Send Email
  msg = smtplib.SMTP('localhost')
  msg.sendmail(send_from, send_to, message_container.as_string())
 
  return 
 
 
#===================
# Main starts here
#===================
 
# Variables can be built by creating strings and adding to it. Example:
my_prebuilt_message = ""
my_prebuilt_message += "\n<li> Item 1 </li>"
my_prebuilt_message += "\n<li> Item 2 </li>"
 
# Create HTML formatted message
  email_html = """\
<html>
<head></head>
<body>
<b><u>My Email Message</u></b>
 
<p>
<b>Hello,</b>
<ul>
{my_message}
</ul>
 
<p>
</body>
</html>
"""
 
  # Variable mappings for email_html string above ( 'label': python_variable )
  email_html_variables = {'my_message': my_prebuilt_message}
 
  # Send Email
  print("-> Sending email...")
  email_subject = "My Email Subject"
  send_email(email_from, email_to, email_subject, email_html.format(**email_html_variables))

  • python_wiki/send_email.txt
  • Last modified: 2019/05/26 03:50
  • (external edit)