How To Send Text Emails In Python


Sending email in Python is easy if you have access to an SMTP server. These are often provided as part of a web hosting account or by email providers. The details are those that would be required to send email using Outlook, Thunderbird or other third-party mail client.

The required SMTP details are:

  • SMTP server domain
  • Username
  • Password

Once you’ve got the details you can update the example code below and begin sending text emails.

# Import required libraries required for email functions
import smtplib
from email.mime.text import MIMEText

# Define email addresses to use
addr_to   = ''
addr_from = ''

# Declare SMTP email server details
smtp_server = ''
smtp_user   = ''
smtp_pass   = 'abcdefghijkl'

# Construct email
msg = MIMEText('This is a test email')
msg['To']      = addr_to
msg['From']    = addr_from
msg['Subject'] = 'Test Email From'

# Send email via SMTP server
e = smtplib.SMTP(smtp_server)
e.sendmail(addr_from, addr_to, msg.as_string())

Sending to more than one address can be done by joining multiple addresses with a comma and a space. If you define a list of email addresses in a list called “recipients” you can join them together using this line :

recipients = ['','']
msg['To'] = SEPARATOR.join(recipients)

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.