Altough Google provides Gmail API to access GMail accounts to send emails, I find it cumbersome to go through OAuth process to send a simple email from a single account. Therefore, I will explain how to send emails on GMail through an SMTP connection.
Step 1. Assuming that you already have a GMail account ready to use, we need to enable Less Secure Apps for that account here, to be able access through SMTP.
Step 2. Now we need to getSMTP settings for GMail server to use in our Python code. The required settings are mentioned here as:
- server: smtp.gmail.com
- Requires SSL: Yes
- Port for SSL: 465
Step 3. Now that we have all the settings we need, we can send an email using smtplib.
1import smtplib, ssl 2import os 3 4def send_email(sender, password, to, message): 5 server = smtplib.SMTP_SSL( 6 host="smtp.gmail.com", 7 port=465, 8 context=ssl.create_default_context()) 9 server.login(sender, password) 10 server.sendmail(sender, to, message) 11 server.close() 12 13 14if __name__ == "__main__": 15 to = "firstname.lastname@example.org" 16 message = """\ 17 Subject: Hello world! 18 Test message.""" 19 20 send_email( 21 sender = "email@example.com", 22 password = os.environ["GMAIL_PASSWORD"], 23 to=to, 24 message=message)
I would like to explain what the code is doing briefly.
- Line 4: We implemented a function send_email at line 4.
- Line 5: Create an SSL connection with a settings as described in Step 2.
- Line 9: Login to our gmail account using sender email and password.
- Line 16: The email starting with the Subject line “Subject: Hello world!”, followed by the body text, “Text message”.
- Line 21: We call our function using the provided parameters.
- Line 23: Please store your passwords as environment variable and load from there, never type into your source code and especially under version control. Even if you delete it later, it will be always stored in the history of commits.