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 = 'firstname.surname1@example.com'
addr_from = 'firstname.surname2@example.com'
# Declare SMTP email server details
smtp_server = 'mail.example.com'
smtp_user = 'my.email@example.com'
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 How2Code.co.uk'
# Send email via SMTP server
e = smtplib.SMTP(smtp_server)
e.login(smtp_user,smtp_pass)
e.sendmail(addr_from, addr_to, msg.as_string())
e.quit()
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 = ['name1@example.com','name2@example.com'] SEPARATOR = ', ' msg['To'] = SEPARATOR.join(recipients)
