How to Write an Email Using Python
In this tutorial, we will learn how to compose and send emails using Python. We will use the built-in smtplib
library, which allows us to connect to an SMTP (Simple Mail Transfer Protocol) server and send email messages programmatically.
Step 1: Import the necessary libraries
First, we need to import the smtplib
library, which is included in Python’s standard library.
python
import smtplib
Step 2: Create an SMTP server connection
Next, we need to establish a connection with the SMTP server. We will use a Gmail SMTP server for this example, but you can use any email service provider that supports SMTP.
“`python
smtp_server = “smtp.gmail.com”
port = 587 # SSL: 465 | TLS: 587
Establish a secure connection with the SMTP server
server = smtplib.SMTP(smtp_server, port)
server.starttls()
“`
Step 3: Log in to your email account
To send an email, we need to provide our email credentials (username and password). Make sure to use an app password if you have two-factor authentication enabled for your email account.
“`python
Login to your email account
username = “your_email@gmail.com”
password = “your_password”
server.login(username, password)
“`
Step 4: Compose the email
Now, let’s compose our email with the necessary information such as the recipient’s email address, subject, and body.
“`python
sender = “your_email@gmail.com”
receiver = “recipient_email@example.com”
subject = “Hello from Python!”
body = “This is a test email sent using Python.”
message = f”Subject: {subject}\n\n{body}”
“`
Step 5: Send the email
Finally, we can send the email by using the sendmail
method with the sender, receiver, and the composed message.
python
server.sendmail(sender, receiver, message)
Step 6: Close the connection
After sending the email, we should close the connection to the SMTP server.
python
server.quit()
That’s it! You have successfully sent an email using Python. Remember to modify the email account credentials and the SMTP server details according to your own requirements.
Feel free to explore additional functionalities provided by the smtplib
library, such as attaching files or formatting the email contents further.
Happy coding!