In this article, learn how to build a script that will automate sending emails in Python.
First, begin by importing all the dependencies required to build the script.

import smtplib

from email import encoders

from email.mime.text import MIMEText

from email.mime.base import MIMEBase

from email.mime.multipart import MIMEMultipart

SMTP stands for Simple Mail Transfer Protocol. SMTP is a protocol that allows users to send emails using Python. This involves sending and receiving mail between servers.

First, for Google to allow emails to be sent, you will need to authenticate in your Gmail account to allow external code to send mails via your email account.

To do this, navigate to your account and click on manage your Google account, navigate to the security page, scroll down to the Less secure app access, and toggle the switch from off to on. This is not recommended by Google as by doing this your account becomes less secure.

Note that as of the time of writing this article, most SMTP servers do not accept port 465 (SSL). This is because it is a deprecated port for email sending, therefore SMTP servers accept port 587 (TLS). Therefore, ensure that you connect to the server using the correct port to avoid future errors.

Next, navigate to the App password section in your Google account security page, enable 2-step verification, and click on the app password. After entering the account password, in the select app list select mail and on the device, select Other (custom name) and write a custom name. A 16-digit password will be generated which can then be used in the password.txt file created for authentication.

To proceed, define a server and a port.

server = smtplib.SMTP("smtp.gmail.com", 465)

server.starttls()

To start the service, use the ehlo command.

server.ehlo()

Next, log in to an existing account by providing an email and a password.

In this case, it is recommended that the password is stored in a text file in the working directory, open and read the text file to get the password. Note that for security purposes you can encrypt and decrypt the text file containing the credentials for the account being used to send the emails.

The next step is to log in to your mail by providing an email address, i.e.: the sender's address.

with open("password.txt", "r") as f:

    password = f.read()

server.login("yourEmailaddress@gmail.com", password)

The next step is to create the message to be mailed. This includes the recipient, sender, subject, body, and even any attachments.

This is done using the libraries imported, which enable the creation of the message of the email to be sent.

Note that Multipurpose Internet Mail Extension is a standard encoded file format used by emailing applications. This is most commonly known as MIME.

  • from email import encoders

  • from email.mime.text import MIMEText

  • from email.mime.base import MIMEBase

  • from email.mime.multipart import MIMEMultipart

msg = MIMEMultipart()

msg["FROM"] = "Mr Test Email"

msg["TO"] = "recipient@gmail.com"

msg["SUBJECT"] = "Build a Python Email bot"

For this example, the message will be loaded through a pre-written text file that contains the contents of the body of the mail.

with open("message_text.txt", "r") as f:

    message = f.read()

In the line of code below, attach the text file as plain text using the MIMEText module.

msg.attach(MIMEText(message, "plain"))

So far, the script can add the header contents and the body of the mail.

Before sending the message, add some lines of code that will enable attachments to be added to the email.

attached_file = "sample_img.jpg"

attachment = open(attached_file, "rb")

The next step involves creating a payload object. This will create a stream that will process the image data of the attached file.

payLoad = MIMEBase("application", "octet-stream")

payLoad.set_payload(attachment.read())

The next step then encodes the image that has been read, then adds a header to the attachment, and then appends the attachment to the message.

Next, convert the entire message into a string, and to send the email, provide the email of the sender and the recipient followed by the string that will be emailed.

encoders.encode_base64(payLoad)

payLoad.add_header("Content-Disposition", f"attachment; filename={attached_file}" )

msg.attach(payLoad)

text = msg.as_string()

server.sendmail("yourEmailaddress@gmail.com", "recipient@gmail.com", text)

server.quit()

Conclusion

In later articles, you will learn how to automate this Python script to allow you to send emails continuously by making the code dynamic. You will also learn how to implement text-to-speech into the bot and also how to add a mailing list to the Python bot.

As always, the script can be found on my GitHub repository https://github.com/IBepyProgrammer/Email-Bot.

If you found this article helpful consider subscribing and sharing.

Thank you.