Python

Google - Where Does It Use Python?

Some people may be under the impression that just because Python is a beginner-friendly language, that experts won’t use it - this simply isn’t the case. Python is used by beginners and experts alike; it is a dynamic, short and flexible language which can be written and read by anyone. Today I’ll be covering some real world examples of Google applications using Python.

Google App Engine

An app engine is a cloud service which is a platform that allows the hosting of modern web applications and mobile back ends. Google App engine was originally developed for Python but now offers a range of languages such as Go, Ruby, Java and many more. Despite this, it still allows the usage of Python’s many libraries and tools for hosting web applications.

Google Data Libraries

Google has developed many client libraries for developers to use. For example, Google Data Python Client library is a popular choice for application development in many Google data services. Alternatively, other libraries include libraries for Google Adwords Python Client libraries for accessing Google accounts or many more examples which can be found here.

Youtube

youtube.png

Probably the most famous example is Youtube. Almost everything about Youtube utilises Python in some way - the API and core functionality. For instance, Python is used to view videos or control the templates for the websites. Although, Python is rumoured to be compiled into Go to make up for its performance issues, Python is used in Youtube for its rapid development time and easy syntax.

These are three prime examples of Google using Python — clearly Python is not just for beginners.

Why not try and learn or improve your programming skills in Educademy? Here at Educademy, we offer an introductory Python summer camp course for kids aged 7-16 and an intermediate one. On top of this, we also teach so many different languages! Read more here!

Author: Sophie Dillon

Python in Healthcare

Python is a programming language typically used for developing applications quickly and securely. Python has many real world usages and big communities dedicated for things like machine learning and web development. Notably, this language is commonly used in the healthcare sector for development.

Roam Analytics

Roam Analytics is a startup business based in Silicon Valley. Their approach is data-driven as their company offers a unique analysis of different patients health journeys through machine learning and natural language processing. Essentially, their approach is structured through a deep analysis of data. This allows doctors to have data which will allow them to make better decisions when it comes to the treatment of diseases as they will know what works best. This company utilises Python as one of their languages to code their healthcare application.

AiCure

AICure is also a startup based in New York. This company is an advanced data analytics company; it offers a platform for AI to monitor patient behaviours relating to a medication which the patient takes, which can be used to identify patterns or trends from the data gathered. For instance, it can gather information about a patient like their level of expressiveness through the camera on their phone. This platform will then provide an understanding of a drugs effectiveness which can reduce costs for drug trials for the patients. Therefore resulting in a very effective smartphone application for the health sector!

The Future

There are many different ways that Python can be used in the future in healthcare but a current relevant example is predicting how on a disease may progress. For instance, it is possible to create a cancer survival prediction model in Python. Python has been used to predict the mortality rate of a patient with a specific disease given electronic health records. These models are highly beneficial within the health care industry and uses methods like machine learning to further benefit doctors, patients and the healthcare sector in general.

python.jpeg

There are many possibilities for Python to be used in the future to benefit the healthcare sector. Machine learning is a revolutionary way forward and could potentially be used to save billions. Python is the go-to language for industry experts in machine learning which can truly be used to make a difference in people’s lives.

If this idea intrigues you, why don’t you consider taking our programming courses? Our Python course covers not only knowledge you’ll gain in secondary school but other topics like artificial intelligence to help you gain the knowledge to make a difference, too.

Author: Sophie Dillon

Gmail Part 3 - Securing Your Passcode

If you have not read this blog post, I would recommend reading Gmail part 1 and part 2. In this blog post I will be covering how to secure your passcode in Python using the previous pieces of code I have made. The previous pieces of code would look like this:

An example image of what my previous script would look like.

An example image of what my previous script would look like.

So, your passcode would be stored out in the open which wouldn’t be very secure. To solve this issue, we are going to make this more secure through the usage of a JSON file. This is a file type that is primarily used for transmitting information which in our case would be suitable for our Python program.

1) DEVELOPING A JSON FILE

To start with, let’s make a JSON file of where we’re going to store the contents of the email and password. The file should look something like this:

An image example of what the JSON file should look like.

An image example of what the JSON file should look like.

Specify the email and password to be in quotes specifically. This is where we are going to store the email and password. So it should be something like:

{ 
    "email": "exampleemailhere@gmail.com",
    "password": "16characterpasswordhere"
}

So instead of your email and password being stored in the clear in the Python file, we’re going to store the email and 16 character password specifically in this file. Save the JSON file in the same directory as your Python file, so that the file knows what JSON file it is accessing. I’ve saved mine as “Json.JSON”. Now we’re going to edit the Python file.

2) Editing the python file

Okay, so we’ve added information to the JSON file. Now we’re going to have to change the Python file. I will be using the example code from my first blog post regarding this

An image of my altered code from my first blog post.

An image of my altered code from my first blog post.

2a) explaining the code

I have added the Json library to my Python file script. Next, I have told my program to open the Json file as a file. Next, I have stored everything that is collected from the file as a dictionary. So what will be stored in this dictionary is an email and a password, as this is how the JSON file was defined. Next, I have defined the variables “PERSONAL_EMAIL” and “PASSWORD” to access the information in the seperate file which is more secure compared to sensitive information being stored in plain sight in the python file. Next, I have edited the code so that I can test if the email will actually send to me and the JSON file method was successful.

3) receiving the email

If you have defined the JSON file successfully, run the program and you should receive a test email like so:

An image example of a test email I have received

An image example of a test email I have received

If the transmission is unsuccessful an error will be thrown. It’s important that the .py files that you have and the .JSON files are in the same directory, otherwise this will not work!

Note for the second script that the IMap Tools library works by reading from the first message ever in your inbox. Therefore if you have a lot of messages that are seen and not deleted, the program will be incredibly slow at generating new files for the messages that you have not already read.

To summarise, having a .JSON file is an easier and more secure way to store your information rather than storing the information directly in a variable. To learn more about .JSON files, be sure to read more here.

Author: Sophie Dillon

Web Scraping in Python

Web scraping is the process of gathering information from the Internet. This is often employed to extract large amounts of data from websites. Even copy-pasting the lyrics of your favorite song is a form of web scraping! However, the words “web scraping” usually refer to a process that involves automation. The large amount of data on the internet is a great resource for research or your own personal use; however, due to this large amount of data it can be difficult to get the right data that is useful to you. In this blog I’ll go over why you might want to use web scraping and how to do this using Python.

There are many reasons why you might choose to use web scraping. Often when you need to compile a lot of data, for research or personal use, it's a lot easier to write a program to do this for you instead of having to spend loads of time compiling the data yourself. This is particularly prevalent while training machine learning algorithms which often require a large amount of data to learn.

Web scraping is also often used as a quick solution to get a specific piece of data quickly, especially if there is no API (application programming interface) which can be used.

Some of the challenges of creating a web scraper program is the continuous growth of the world wide web. Website technologies are constantly changing and there is no website which is the same. This requires each website to require its own personal treatment if you want to extract the information that’s relevant to you. Another major challenge is durability. Websites are constantly changing and are in active development. Once the website structure changes, your web scraper might not work. This requires you to be constantly aware of changes to website structures so you are able to fix any issues quickly by updating your web scraper.

Creating our own web scraping program

We will be creating a basic program that scrapes song lyrics off web pages and writes them to a file.

bs.jpg

To start you will require to install two Python packages:

  • requests for performing your HTTP requests

  • BeautifulSoup4 for handling all of your HTML processing

You can install these dependencies with pip:

pip install requests BeautifulSoup4

At the top of our Python file we need to import the relevant modules that we require in our program.

imports.PNG

Next we need to create a function which downloads the web pages. The requests package allows us to do all things HTTP in Python. We have created a function here called getContent() which attemps to get the content at the parameter URL by making a HTTP GET request. If the response it good it executes getLyrics() function which we will see later else prints that the song cant be found. If an error occurs during the request the logError() function will be called with the parameters of the error.

1.jpg

If the response is an HTML response then isGoodResponse returns True, otherwise False is returned.

2.jpg

If an error occurs while running the HTTP GET request the logError function is run and prints the error to the console.

3.jpg

Once we know the response is actually an HTML response we can start parsing the HTML response. We can do this using the BeautifulSoup4 module which we have imported at the start. After parsing we can find specific html elements which we can use to get the lyrics from the web page. Once we have the lyrics, we call the writeToFile() function with input parameter of the lyrics.

4.jpg

This short function writes the lyrics to a file called lyrics.txt which is located in the same folder as this Python script. It will either create the file if the file is not there or replace any text in the file already with the new lyrics.

5.PNG

Lastly, we will create a main() function which is used to get the relevant data from the user before passing on the data to the getContents() function. At the end of the code we will call the main() function.

main.PNG

Hopefully by now you have created a working program which you can actually use to get lyrics for songs! This is just the start of what you can use the BeautifulSoup4 and requests modules for.

Would you like to learn more about python?

Join us at one of our Online Summer Camps for Kids and Teens to learn more about the cool things you can do with Python and with other programming languages!


Author: Robert Nimmo

References:

  • https://funthon.files.wordpress.com/2017/05/bs.png?w=772

  • https://www.antevenio.com/usa/wp-content/uploads/2019/12/web-scraping-1024x536.jpeg

Why learn Python?

If you’re thinking of learning Python, or if you recently started learning it, you may be asking yourself: 

“Why learn Python and what exactly can I use Python for?”

ezgif.com-webp-to-jpg.jpg

Learning any programming language is becoming more and more important due to how digitally connected we all are. There are many programming languages but very few find the right balance between powerfullness and simplicity. Python is one of the few exceptions. Currently Python is one of the most popular programming languages used right now in large companies and startups. Large companies like Google, Spotify and Netflix are all using Python on a daily basis, so there is a good chance you have been using something that runs using Python even if you didn’t realise it was.

Not only is Python popular but it is also a great starting language to learn, with its simple and concise syntax which helps you not get confused while writting your Python code and with help from Pythons large collection of libraries you are able to do so much from the beginning. Problems which are complex in other programming languages can be completed in 1 or 2 lines of code in Python due to how beginner friendly Python is. This allows you to start making Projects you actually want to do very quickly.

Snake Game - One of the projects covered in our course

Snake Game - One of the projects covered in our course

Python is especially powerfull and useful when dealing with large collections of data as its very easy to manipulate this data using Python efficently. This is a large reason large companies are flocking to use Python. But that doesn’t mean Python is only useful for manipulating data; You can do so much more with Python! Did you know you could create games, build websites and even develop AI and machine learning programs in Python!

By having a good understanding with Python, it will help you learn more complicated programming languages in the future, for tasks that Python is not as good at, and improve your problem solving and creativity skills. Alot of universities are also using Python as the first languages that they teach their students, so learning early will give you a great headstart if you plan to study Computer Science at university!

So why not join one of our online Python summer camps and we will explore the cool projects you can develop in Python together.

print ("I love learning in Python!")

How does Artificial Intelligence and Machine Learning work?

Artificial Intelligence and Machine Learning are two buzzwords that have blown up in the 21st century, and whilst many of us now know what they are, what’s the difference, how do they actually work, and are robots going to take over the world? I can safely say that no, robots are not going to take over the world anytime soon because AI is nowhere near that advanced as of yet, they are very good at completing one task. For example, there has been a huge rise in AI being used in the healthcare sector, especially tumour analysis, but if you were to give that algorithm a picture of an apple and ask it what it is, it would not have a clue. For more detail on what AI is see this article posted recently.

article-pic.png

Artificial Intelligence, AI, is the bigger picture. It is the overarching field of research that encompasses topics such as, Machine Learning, ML. The two stages of ML are training and inference. First we must train the model using data that we have collected and then we used the trained model to infer suggestions based off of the data collected. There are two main paths to take: Supervised Learning; and Unsupervised Learning. The major difference is that Supervised is based on labelled data whereas Unsupervised in based on unlabelled data which affects the way we feed the data to the algorithms. Supervised learning algorithms, namely K-Nearest Neighbour, KNN, are used to solve two types of: classification; and regression.

KNN assumes that similar data exists in close proximity to each other, hence clustering k pieces of data together. It can be used for classification and regression but it is far more frequently used for classification, so once the data has been collected the model must now be trained. When training the model a train/test split is applied to the data, a training set which would be used to train the model and then a test set which would calculate the accuracy of the model by measuring the distance between the predicted value and the actual value. This can often take form in a confusion matrix. Then once a certain accuracy is achieved the model could be used on data where the correct output is not known.

KNN is one of many different types of algorithm in both AI and ML. Searching algorithms are also very common in the field and have been widely publicised in the media through IBM’s Deep Blue and Deepmind’s AlphaGo. In the example of AlphaGo, Deepmind’s vision was to create an algorithm that could be the best in the world at the game Go. Go is an abstract strategy board game for two players, created in China, in which the aim is to surround more territory than the opponent. The deepmind team based AlphaGo on the Monte Carlo tree search algorithm which is a heuristic search algorithm, often used in these decision making games. In March 2016, AlphaGo beat Lee Sedol, a professional 9-dan rank Go player, proving the power of AI.

Intrigued?

Depending on your age, interacting with AI can come in different forms. Here at Educademy, we offer two AI courses in Scratch and Python, where you can learn how you can incorporate AI into your own life.

Reading Gmail with Python - Part TWO

email-4800274_960_720.png

This is a follow-up to my previous blog from my automating reading Gmail messages with Python. If you haven’t checked it out yet, read that blog post before this one.

Another cool thing you can do with Python is reading emails using the Python. In this blog post, I’ll be using a library called “IMAP tools”. IMAP refers to an Internet Message Access Protocol. Unfortunately, Yagmail can only send emails so we’ll have to install a new library in this blog post. If you’re curious, you can read the documentation for that library here.

INSTALLING IMAP TOOLS

Similarly to last time, we’re just going to type in “pip install imap-tools”. Alternatively, you can use an IDE like VSCode and use the terminal there!

PYTHON SCRIPT

from imap_tools import MailBox, AND, MailMessageFlags
PERSONAL_EMAIL = 'yourpersonalemailhere@gmail.com'
PASSWORD = '16passhere'

def check_message(msg):
    filename = "".join(char if char.isalnum() else "_" for char in msg.subject) + ".txt"
    with open(filename, "w") as file:
        file.write(msg.text)

with MailBox('imap.gmail.com').login(PERSONAL_EMAIL, PASSWORD) as mailbox:
    for msg in mailbox.fetch():      
        if MailMessageFlags.SEEN not in msg.flags: 
            check_message(msg)

I’ve wrote the code entirely myself using the iMap Tools library. The code I’ve wrote checks if a message is unseen. If it is a new text file containing the emails subject and inner text will be created.

An example image of a new folder

An example image of a new folder

Before Running the Program

Firstly, create a new folder and store the Python file within this folder. This will be where all the unseen emails will be stored in .txt files.

  1. The Variables and Importing the Library

from imap_tools import MailBox, AND, MailMessageFlags
PERSONAL_EMAIL = 'yourpersonalemailhere@gmail.com'
PASSWORD = '16passhere'

Here, I’m importing the necessarry things from the library and am declaring the constants that we’ll be using. In the PERSONAL_EMAIL variable, store your gmail email and in the password variable, enter your 16 character password that was received in part one.

2. The Library Using Gmail

with MailBox('imap.gmail.com').login(PERSONAL_EMAIL, PASSWORD) as mailbox:
    for msg in mailbox.fetch():      
        if MailMessageFlags.SEEN not in msg.flags: 
            check_message(msg)

Firstly, we’ll log in with the supplied username and password in the mailbox. Next, we use a for loop to get each message in the mailbox. For each message, if it is not seen, we’ll call a function to store the message subject and text to a .txt file.

3. The Check Message Function

def check_message(msg):
    filename = "".join(char if char.isalnum() else "_" for char in msg.subject) + ".txt"
    with open(filename, "w") as file:
        file.write(msg.text)

This function will check if the file name is appropriate and doesn’t contain any character that Windows can’t recognise in the subject line e.g “?”. This will then store the subject name as the .txt file. The new file name will then be written to a new file and the message text will be stored in the respective text file. This rinses and repeats for every message.

An example image of the final output

An example image of the final output

Quite a simple program but it works rather well if you want all your emails stored somewhere!

Author: Sophie Dillon

What is Artificial Intelligence and Why is it so Important?

Artificial Intelligence. It’s a phrase that’s been thrown around a lot in the past few years, but what really is it? For most people, what initially comes to mind is probably the idea of talking robots that are capable of passing as human. For some people, AI might even spark fear - probably because of sci-fi movies like I, Robot that involve dystopian worlds in which the human race has been destroyed by the very robots they created to help them! In reality, AI is indeed the idea of trying to make computers think like humans, but at it’s core all it really is, is the the combination of massive amount of data with some clever algorithms.

Where did it all start?

John McCarthy in 2008  Source : Jeff Kubina

John McCarthy in 2008
Source : Jeff Kubina

The idea of AI has been around for centuries - people have been obsessed with trying to create machines to do things for us. However, the term Artificial Intelligence was first coined by John McCarthy (an American Computer Scientist) in 1955 and shortly after in 1956 he organised the infamous Dartmouth Conference, which is where AI was first established as an emerging field of research.

Getting into the Jargon

“Machine Learning”, “Neural Networks”, “Deep Learning” - these phrases (and many more) appear time after time whenever we hear about Artificial Intelligence. They’re all important constituents which make up the field of AI, but what do they actually mean?

  • Machine Learning
    Machine learning can broadly be split into two categories: supervised learning and unsupervised learning. Take, for example, trying to predict housing prices based on how many bedrooms a house has. We would give the computer a training set - this would contain the number of bedrooms for lots of different houses, and how much that house sold for. We use this data to train the computer, and from it the computer learns how to predict housing prices of other houses based on the number of bedrooms. This is supervised learning because we are giving the computer examples and telling it the outcome in order to train it. In contrast, in unsupervised learning, data is given to the machine but there are no outputs (e.g. the price of the house) - instead we ask the computer to make inferences based on the inputs only.

  • Neural Network
    Neural networks are algorithms which have been designed to mimic how the brain works. They are a type of supervised learning algorithm. We give the computer input data with a labelled response, and we design some sort of path in which the data is processed - this path is the neural network. The paths in between the input and output layers are called hidden layers. Algorithms can have any number of hidden layers - this is decided by the programmer.

  • Deep Learning
    Deep learning is any type of machine learning that involves neural networks, but these neural networks have lots and lots of hidden layers (hence the term “deep learning”.

  • Computer Vision
    Computer vision is anything concerned with teaching computers how to “see”. Essentially, we want computers to draw data from images and videos, and this is generally done using deep learning algorithms.

  • Natural Language Processing
    Natural Language Processing (or NLP for short) is an interdisciplinary field which draws on knowledge from linguistics, computer science and AI. It involves training computers how to process human language - whether as speech or text - and often make inferences from this data.

Source: DataCamp

Source: DataCamp

AI in the Modern World

It goes without saying we, as humans, are unbelievably dependent on technology everyday. What you might not have realized, however, is that you probably use AI all the time. How did you find this article? Maybe you asked Siri to find you an article about AI, or you typed “Ariticial Intelligence” into Google and this article popped up. Either way, AI was at the core of your search. Another example that we all take for granted are spam filters in our email inbox - gone are the days of missing an important bill because it was hidden in a cloud of spam! Instead, our inboxes automatically send irrelevant emails to the spam folder (most of the time…).

But there are some even more interesting uses of AI that researchers are working towards in the hope of improving the world we live in:

  • Improving accuracy and wait time of cancer Diagnoses

  • Reducing bias in criminal justice

  • Driver-less Cars

  • Understanding and fighting climate change

Intrigued?

Although it sounds super complicated, there are some amazing resources out there to teach you more about the algorithms behind AI and the impacts AI can have on society. Here at Educademy, we offer courses in AI for kids as young as 7 in two different programming languages - Scratch and Python.

If you want to read some more about AI in the modern world, I would highly recommend reading Hannah Fry’s Hello World: How to be Human in the Age of the Machine. It’s a great introduction for pretty much anyone of any age or ability into the world of AI. She also hosted a podcast with AI Giant DeepMind in which she interviews some of the best researchers in the field. You can listen to the podcast here or on whatever app you use to listen to podcasts.

Cover Photo Source: Franck V


Author: Richa Lad

Where Should I Host My Python Project?

So you have finished your Python project and want to share it with your friends and family, however, you don’t know where to start. Well this blog post should help you narrow down the options to find the best option for you and your project requirements.

Hosting your project can be the most exciting part when developing your project as you now can share your hard work and talent with everyone else; however, this can also be one of the most frustrating and sometimes complicated parts due to the number of options out there and complexity of hosting your project.

The first question you have to ask yourself is what type of project is it? Are you using a web framework, such as Django or Flask; Are you wanting your code to be scheduled to run automatically at a certain time of day; Are you using a graphical library such as PyGame or Turtle; Or are you just wanting to host a console (command line) application. Depending on how you answered this question depends on where you end up hosting your project. 

Web framework hosting

This is the most common reason why you would probably be hosting a Python project. Web frameworks in Python, such as Django and Flask, are currently a very popular way to create small and large scalable data driven websites due to the simplicity in creating the website and the power of the Python programming language. This has resulted in a lot of hosting sites to support hosting Python web frameworks. Two of the most popular are PythonAnywhere and Heroku.

logo300x300.png

PythonAnywhere

PythonAnywhere is one of the most popular sites for hosting your Python project, especially for small personal projects, and there is a good reason for this. You can host, run, and code Python all in the cloud! Unlike many other hosting sites PythonAnywhere has a free tier for hosting. This is great when you don’t want to spend loads and just want to share it with friends and family. There are limitations with this, however, if you are not expecting your website to have a lot of traffic and don’t mind not being able to change your url this is a great starting place. You can upgrade with your needs later as your website grows in scale. One of the biggest advantages of using PythonAnywhere is the simplicity. You can start hosting your website and project in minutes not hours, this helps considerably with their quickstart installers for Django, web2py, Flask, and Bottle; however they support any WSGI web framework.

2.png

Heroku

Heroku is another great option for hosting Python web framework projects. It requires a bit more work to start hosting and requires you to be comfortable using the command line of your computer. This option also has a free option, just like PythonAnywhere, to help you get started and the price goes up depending on how much traffic you are expecting and more advanced functionality. One benefit of Heroku over PythonAnywhere is the ability to use websockets in your project, which is not able to be done in PythonAnywhere at the time of writing.

There are other Python web framework hosting sites; however, these are the two easiest and most popular ways. These web hosting sites take out all the hard work of hosting. You don’t have to worry about setting up a database and you can get help if something goes wrong. When your websites start growing you can quickly scale up easily without having to worry about any problems.

Scheduling a Python Script to run

Pythonanywhere

If you are wanting to schedule a Python Script to run at certain times of the day, hosting your script in the cloud might be the easiest option. The easiest place to do this is using PythonAnywhere. PythonAnywhere allows you to quickly set up a task to run the python script to run daily at a particular time of day, or for paying customers hourly at a particular number of minutes past the hour. It's rather like a simple version of Unix's cron utility. This allows you to quickly get your tasks scheduled and up and running.

heroku

Heroku is another way to schedule a python script to run. This is a bit more complicated to set up as it isn’t by default a feature of Heroku. You will have to add an add-on to your dyno. There are many add-ons available for this so you can just choose the best for you. One of the most advanced feature rich add-ons for this job is advanced-scheduler

3.png

aws lambda functions

Another way to schedule a Python Script is using an AWS Lambda functions. AWS lambda functions allow you not only schedule a script at certain times of the day but also when a certain event occurs, such as an inbound HTTP POST comes in to API Gateway or a new file is uploaded to AWS S3. This will require a bit more work to set up, but might be beneficial if you want to do more with your Python script.

Hosting a graphical (Turtle, PyGame) or console based project

trinket-logo-notag-white.png

Trinket

The best way to host a graphical project, like Turtle or PyGame, or a console application is using Trinket. Trinket allows you to share code from any device and lets you run and write code in any browser, on any device. It works instantly, with no need to log in, download plugins, or install software. And you can easily share or embed the code with your changes when you're done. Both PyGame and Turtle projects can be hosted using Trinket. Once you have created your Trinket, you can easily share the project by sharing the link, or by embedding the Trinket in a website. This is a great way to add Python projects to your website, especially if you want to host games created with PyGame and requires very little work to set up! One downside to Trinket is there are a limited number of external modules that you can use which could limit more complex projects.

Here is an example of Trinket being embedded into a web page. This is also one of the projects we do in our Introductory Python Course!

Hopefully you now have been able to choose the best option for your needs and now can start hosting your exciting projects which you can share with everyone else!

Do you want to learn more about Python?

Join us for our Online Summer Camp For Kids and Teens to learn more about Python and many other programming languages.


Reference

  • https://img.stackshare.io/service/4940/logo300x300.png

  • https://www.brandeps.com/logo-download/H/Heroku-logo-vector-01.svg

  • https://www.factor-a.com/wp-content/uploads//2019/05/Dayparting_Ad_Scheduling_Amazon_Sponsored_Ads-e1563961091588.jpg

  • https://www.netclipart.com/pp/m/348-3487927_transparent-aws-lambda-icon.png

  • https://trinket-app-assets.trinket.io/logo/PNG/stacked/trinket-logo-notag-white.png

Author: Robert Nimmo

Automating Gmail with Python

Image credit: Schoithramani on Pixabay

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

bp2.png

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.

An image of the command prompt

An image of the command prompt

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:

A test email sent to myself through Gmail.

A test email sent to myself through Gmail.

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