INTRODUCTION.
In today's digital age, automated emails have become an essential part of many business and personal communication workflows. Whether it's sending notifications, updates, or personalized messages, automating the email-sending process can save a whole lot of time and effort. In this article, we will explore how to send automated emails with Gmail using Python.
REQUIREMENTS.
- A Gmail account.
- Python Installation.
Python provides powerful libraries and modules that make it relatively easy to automate email sending. We will be using the smtplib
and email
module. smtplib
is a built-in library in Python, along with the Gmail SMTP server to send emails. Python's email
module is a powerful library that provides functionalities to create, manipulate, and send email messages. It allows you to construct email messages with various components such as headers, subject, body, attachments and more.
CONTENT.
Setting Up Gmail.
Before we dive into the coding part, there are a few prerequisites and setup steps you need to follow to enable automated email sending through Gmail.
- Enable 2-Step Verification (just a security measure).
- Generate an App Password.
Enable 2-Step Verification.
To ensure your Google account is safe, you need to enable 2-Step Verification. Go to your Google Account settings, navigate to the Security section, enable the "2-Step Verification" option.
Generate an App Password.
This part is the most important. To enhance security, Google requires an app-specific password for programs like Python to access your Gmail account. To generate an app password;
Go to your Google Account settings and navigate to the Security section, select “2-Step Verification” and scroll to the bottom, then select “App Passwords”.
Select “Other (custom name)” and give it any name of your choice, then click “Generate”.
Yay!!!, you’ve successfully generated your app password. Be sure to copy the generated password and save it somewhere safe because once you close the interface, you won’t be able to see the password anymore.
Now that we have the necessary setup in place, let's proceed to the coding part.
Writing the Python Code.
To send automated emails using Python, you need to import the smtplib
and email
module, and configure it with your Gmail account credentials and the SMTP server settings.
from email.message import EmailMessage
import ssl, smtplib
def automated_email():
email_sender = 'youremail@gmail.com'
email_password = 'your-generated-password-here'
email_reciever = 'reciever-email-here'
subject = 'Your Email Subject'
body = """
This will contain the contents of your email.
This will contain the contents of your email.
This will contain the contents of your email.
"""
# Create an instance of EmailMessage
em = EmailMessage()
em['From'] = email_sender
em['To'] = email_reciever
em['Subject'] = subject
em.set_content(body)
# Create a secure SSL context
context = ssl.create_default_context()
# Connect to the SMTP server and send the email
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
# Login to the email sender's account
smtp.login(email_sender, email_password)
# Send the email
smtp.sendmail(email_sender, email_reciever, em.as_string())
The email sender's address, password, and the recipient's email address are set in the email_sender
, email_password
, and email_reciever
variables, respectively.
Note: Make sure to replace the placeholder values with your valid Gmail account information, including the email sender's address, password, and recipient's email address. Keep your email credentials secure and consider using environment variables to store sensitive information.
If you would like to format the email content with HTML tags, this is an updated version.
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import ssl, smtplib
def send_mail():
email_sender = 'youremail@gmail.com'
email_password = 'your-generated-password-here'
email_reciever = 'reciever-email-here'
subject = 'Your Email Subject.'
content = """
<html>
<body>
<b>Hi</b></br>
<p>This email is html formatted.</p>
</body>
</html>
"""
# Create an instance of MIMEMultipart for composing the email
em = MIMEMultipart()
em['From'] = email_sender
em['To'] = email_reciever
em['Subject'] = subject
# Attach the content as HTML to the email
em.attach(MIMEText(content, "html"))
# Create a secure SSL context
context = ssl.create_default_context()
# Connect to the SMTP server and send the email
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
# Login to the email sender's account
smtp.login(email_sender, email_password)
# Send the email
smtp.sendmail(email_sender, email_reciever, em.as_string())
Here, an instance of MIMEMultipart
is created to compose the email. The email's sender, recipient, and subject are set using the corresponding headers in the MIMEMultipart
object. The content of the email, passed as the content argument, is attached to the email as HTML using MIMEText
.
The above codes provide a basic example of sending automated emails with Gmail using Python. However, you can enhance and customize the functionality based on your requirements. Here are a few ideas:
-
Adding Attachments: You can use the
email
module in Python to create more complex email messages with attachments. This allows you to send files along with your automated emails. -
Email Templates: Instead of composing the email content within the code, you can utilize email templates to separate the content from the code. Libraries like
Jinja2
can help you create and render email templates with dynamic data. - Error Handling: Implement robust error handling to handle exceptions and provide informative messages in case of any issues during the email sending process.
-
Scheduled Emails: Use Python's
datetime
module and scheduling libraries like schedule orAPScheduler
to send automated emails at specific times or intervals.
Conclusion
Automating email sending using Python and Gmail can greatly streamline your communication processes. Whether it's sending notifications, updates, or personalized messages, the smtplib
module in Python makes it easy to connect to the Gmail SMTP server and send automated emails. Remember to ensure the security of your Gmail account by enabling less secure app access and generating an app password. With the power of Python and Gmail, you can save time and effort while effectively reaching your recipients.
Top comments (0)