Python 3 – Sending Email using SMTP
Python 3 provides an inbuilt package ‘smtplib’ for sending email using Simple Mail Transfer Protocol (SMTP). SMTP is a protocol for sending email messages between servers. The smtplib package contains classes for handling SMTP protocols.
In this article, we will learn how to send an email using SMTP in Python 3. We will use Google SMTP server to send the email.
Setting up the Gmail account for SMTP
To set up a Gmail account for SMTP, you must first enable Less Secure Apps. Follow the steps below to enable:
- Go to https://myaccount.google.com/security
- Click on the “Less secure app access” option.
- Turn on the “Allow less secure apps” button.
Creating the Email
To send an email, we first need to create the email. We use the built-in email package to create the email. Here is an example of creating an email:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
body = "This is a test email"
subject = "Test"
msg = MIMEMultipart()
msg['From'] = "<sender's email>"
msg['To'] = "<receiver's email>"
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
In the above code, we imported the smtplib package, and the email.mime.text and email.mime.multipart sub-packages. We then created the message using the MIMEMultipart() function from the email package. We set the body and subject of the message, and use the MIMEText() function to attach the body to the message.
Sending the Email
To send the email, we use the SMTP class from the smtplib package. Here is an example of sending an email:
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("<sender's email>", "<sender's password>")
server.sendmail("<sender's email>", "<receiver's email>", text)
server.quit()
print("Email Sent")
except Exception as e:
print(e)
In the above code, we created an SMTP object using the SMTP() function from the smtplib package. We then use the ehlo() function to greet the server, and starttls() function to enable encryption. We use the login() function to log in to the sender’s Gmail account, and use the sendmail() function to send the email to the receiver’s email address. We then use the quit() function to terminate the SMTP session.
Conclusion
In this article, we learned how to send an email using SMTP in Python 3. We used the smtplib and email packages to create and send an email. We also learned how to set up a Gmail account for SMTP, and enable Less Secure Apps. SMTP is used widely for sending emails between servers, and Python’s inbuilt package for SMTP makes it easy for us to send emails using Python 3.