One cool thing that you can do with Python is automate sending your own emails through Gmail in Python. This is possible through a simple library called Yagmail - a GMAIL/SMTP client making it rather easy to send emails. You can read the documentation fully here. I’ll be covering step by step how to automate sending out your own emails in Gmail.
Allowing Yagmail Access to Your Gmail
Firstly, in order to write our Python script, we’re going to have to allow access for less secure applications to access our Gmail. By default this is switched to off, so we’re going to have to manually switch this on using the link here. Now, we’re going to create an application password for Python using two-step verification.
Go to the security section of your Google account and now go to app passwords. You’ll be prompted with the option to name your application something. Let’s call it “Python”. Click next and a random 16-character password will be generate for usage in your program. Copy and paste it without any spaces for usage later in your program.
Installing Yagmail
Now, we’re going to have to install the library we need. On a Windows install, “Pip”, our package manager, should automatically come installed with Python.
To open the command prompt, simply search for it in Windows and it will display the screen stated above. Alternatively, if you prefer using a program such as VSCode, you can open a new terminal in there. Now type in “pip install Yagmail” and we’re all set. Now to the script!
Python Script
import yagmail # the library that we are working with # all the necessary login information here user = 'yourusernameemailhere@gmail.com' # your email goes here password = '16passbygoogle' # the password we just generated goes here to = 'whoyouwantgoeshere@gmail.com' # the user you're sending an email to goes here # content information here subject = 'Whatever subject goes here' contents = 'Text here' try: yag = yagmail.SMTP(user, password) yag.send(to, subject, contents) print('Your email was sent successfully') except: print('There was an error sending the email')
Assuming all indentation is correct, we’ll end up with this:
This is how to send an email to someone of your choice through Gmail. If you’re interested in experimenting more around with Yagmail, check out its documentation!
With Thanks To:
Author: Sophie Dillon