Sending Emails with Python
Use smtplib to Automate Your Gmail Account
Being able to send emails automatically is a useful tool, and can come in handy for many projects (e.g. for a crypto bot doing automated trading and notifying the user of executed trades). Thus in this code we’ll show simple and efficient Python code doing exactly that. The shown code works for arbitrary email providers, but we put special emphasis on Gmail — since it is one of the most commonly used email providers. For this, we also show how to generate a required app password.
We begin with this part, and then show and explain the Python code.
Creating App Passwords for Google Accounts
App passwords are special passwords you can create for certain apps and, as Google puts it, “help you sign into your Google Account on older apps and services that don’t support modern security standards”. Nevertheless, we need these to do what we want — namely sending emails programmatically with Python. But, that should go without saying, take good care of your app passwords — anyone in possession of it can access your full Google account in the worst case.
Here’s a nice explanation of how to create app passwords: link.
First, navigate to your Google account and click “Manage your Google Account”, then select the “Security Tab” on the left. According to above linked article, app passwords should be listed in the “How you sign in to Google” section. If you don’t see them, it could be due to one of several reasons, the most common probably not having 2-Step Verification enabled. Thus, to begin, enable this feature. However, I still did not see “App passwords” in that section — but one can manually look for the desired page by using the search bar at the top, and inputting “App passwords”:
Open the page, and follow the instructions to create a new app password. Note it down, as you won’t get to see it again. In the next section I’ll show you how to store it on your computer, and how to use it to automatically send emails.
Sending Emails with Python
Now let’s come to programmatically sending emails with Python. If you are a Google user, you should have setup a required app password as described in the previous section, all others are probably joining here.
Storing and Loading Credentials
First we need to decide how to store the necessary credentials, in particular the password linked to the email account. Storing these in code is never a good idea — code is checked in and visible to all other developers. A better option is to use environment variables, which are stored on your device. We will store email address and password there, and then read these with Python using the os library.
One way of permanently storing environment variables (on Linux) is adding them to ~/.bashrc. Thus, open this file with your editor of choice, and add the following lines to the end of it:
export email_addr="{YOUR_EMAIL}"
export email_pw="{YOUR_PASSWORD}"For the email, paste your full email, in my case this is crypto.explainer.contact@gmail.com. The password is your email password, or, in the case of Gmail, the app password we created above.
Get CryptoExplainer’s stories in your inbox
Join Medium for free to get updates from this writer.
Then, in Python we can query these values via:
self.email = os.environ.get("email_addr")
self.pw = os.environ.get("email_pw")(Note: you need to re-load your terminal for the variables to be updated.)
Sending Emails with smptlib
Now, let’s come to actually sending emails. For this we use smtplib, which is a default module of Python and allows using SMTP services — which is exactly what we need.
We introduce a convenience wrapper class around it which handles sending emails:
import os
import smtplib
from email.mime.text import MIMEText
class EmailClient:
def __init__(
self, smtp_server: str = "smtp.gmail.com", smtp_port: int = 465
) -> None:
self.email = os.environ.get("email_addr")
self.pw = os.environ.get("email_pw")
self.smtp_server = smtp_server
self.smtp_port = smtp_port
def send(self, recipient: str, subject: str, body: str) -> None:
smtp_server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
smtp_server.login(self.email, self.pw)
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = self.email
msg["To"] = recipient
smtp_server.sendmail(
self.email,
recipient,
msg.as_string(),
)
smtp_server.quit()In its constructor, we read the credentials as defined above, and further set a server address and port. The default values point to Gmail — if you use a different provider, I would ask you to google the right ones for your usecase.
The send function then does the actual sending. We first create an SMTP server object, and login with our credentials.
Next, we create the actual message as a MIME object, including sender, receiver and subject.
Eventually we send the message to the receiver, and quit the server.
To send a message (e.g. to me!), you can then use the following code:
email_client = EmailClient()
email_client.send(
"crypto.explainer.contact@gmail.com",
"Test Email",
"Hello,\n\nthis is the body.\n\nCheers",
)Conclusion
In this post we learned how to send emails automatically with Python. We paid special attention to Gmail, but the approach explained here works for all other providers, too. For Gmail, we first explained how to create an app password needed for automatically sending emails.
Then, we moved to the Python code, starting with how credentials can be stored, and then introducing code around smtplib for sending emails.
I hope this was helpful to you, thanks for reading!









