Labels

Arduino (1) Bugs (3) C (1) Install (3) Linux (25) Maths (1) Python (11) Raspberry Pi (4)

Tuesday, 13 December 2016

How to send emails in Python

We are going to be using the yagmail library to send a email using python.

To start of we will need to install the yagmail python library.
pip install yagmail

If you don't have pip installed you can install using the following commands depending on your OS.

Debian systems:
sudo apt-get install python-pip

RedHat/Fedora
sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel


Arch Linux:
sudo pacman -s python2-pip

openSUSE:
sudo zypper install python-pip python-setuptools python-wheel

Now we will test that the library has been installed with a simple python script.

#!/usr/bin/python
import yagmail


Run this script and if it produces no errors you are good to go.

Now we can get started sending emails.

First we need to import the necessary libraries(yagmail, time).
import yagmail
import time


Now lets setup the variables that are going to be sent in the email
subject = "Sent from Python at " + time.strftime("%D:%M:%Y")
message = "Hello, World!"
sender_email = "YOUR_EMAIL"
sender_password = "YOUR_PASSWORD"
recipient_email = "RECIPIENT_EMAIL"


Now lets send the email
yag = yagmail.SMTP(sender_email, sender_password)
yag.send(recipient_email, subject, message)


Putting all of that together we get:
import yagmail
import time

subject = "Sent from Python at " + time.strftime("%D:%M:%Y")
message = "Hello, World!"
sender_email = "YOUR_EMAIL"
sender_password = "YOUR_PASSWORD"
recipient_email = "RECIPIENT_EMAIL"

yag = yagmail.SMTP(sender_email, sender_password)
yag.send(recipient_email, subject, message)


If we run this script you should have a sent a email using less than 10 lines of python.

Link to yagmail GitHub