Sending an email will be a useful feature in any of the applications. In this article, I am going to show you how to send email using your Gmail account programmatically for free with the help of python.
- Gmail configurations
- Saving credentials in environment variables
- Python code
There are two ways to get the credentials for sending mail.
1. Two-factor authentication (RECOMMENDED)
- Add two-factor authentication to your google account.
- Go to the following link – https://myaccount.google.com
- Find and click “security” in the left hand side menu bar
- signing in to Google again
- Enter your mobile number and activate the 2-step verification.
- Come back to the security page under signing in to Google.
- Now click the app password and go to “select app”.
- Click Custom name (give any name)
- Copy the generated password and keep it safe since it can be viewed only once.
2. Local machine testing (NOT SECURE)
- Go to the following link and enable less secure app – https://myaccount.google.com/lesssecureapps
- If ip keeps changing then use following link, https://accounts.google.com/DisplayUnlockCaptcha
Saving credentials in environment variables
NOTE: You can neglect this step if you are doing this for testing purposes and hard coding the credential is acceptable.
- Click on start, and search environment variables and select edit environment variables for your account.
- Click on environment variables under the advanced tab.
- Under system variables, click the “New” button.
- Under variable name, enter “EMAIL” and under variable value, enter the email id that you configured and click OK.
- Similarly, click New again, and enter “PASSWORD” under the variable name and your generated password under the variable value and click ok.
The following code can be found in my repository – https://github.com/ranjithkumarmadhavan/python-projects/tree/main/email%20automation
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_address = os.environ[‘EMAIL’]
to_address = [“TO_EMAIL_ADDRESS”] #add the email id to which you want to send mail
message = MIMEMultipart()
message[‘From’] = from_address
message[‘To’] = ” ,”.join(to_address)
message[‘subject’] = ‘Hello from SMTP’
body = “Hello from Python code”
email = os.environ[‘EMAIL’] #picks from the environment variables we configured above
password = os.environ[‘PASSWORD’] #picks from the environment variables we configured above
mail = smtplib.SMTP(‘smtp.gmail.com’,587)
text = message.as_string()
I have used this specific code many times in my AWS lambda code. Configuring the lambda function with a cron expression to execute on a regular interval can be a very good use case.