Python Program to Send Emails Using Yagmail

With Yagmail, sending e-mail using a Python program is easier than ever before. Yagmail – Yet Another Gmail/SMTP Client is a user-friendly API that simplifies the process of sending emails.

In this post, I am going to share how to use yagmail, the API described above.

If you want to read the full documentation of this API, click HERE.

Python comes with the built-in smtplib module for sending emails using the Simple Mail Transfer Protocol (SMTP). However, it is much simpler to understand and work with yagmail.

But to use yagmail, you will have to install it yourself explicitly.

Installation

You can install it very easily. Its installation packages are found HERE.

You may run either of the two pip commands given below (based on your needs) in your terminal or Command Prompt.

pip install yagmail

pip3 install yagmail

And if you are using Linux distros like Ubuntu, don’t forget to add sudo in front of the command.

Sending Mail Using yagmail

To send an email using yagmail, it involves 4 steps.

  1. Firstly, import the yagmail module.
import yagmail
  1. Create the connection to a SMTP server.
# connect to smtp server.
yag_smtp_connection = yagmail.SMTP( user="sender@gmail.com", password="senders_password", host='smtp.gmail.com')
  1. Create content of the mail.
    • You can add content (subject, attachments, and body) as shown below:
# email subject
subject = 'Hello from THE BHUTAN IO'

# email content with the attached file path.
contents = ['Hello tom this is Sonam trying to send mail to you!']
  1. And send the mail to your receiver.
yag_smtp_connection.send('reciever@gmail.com', subject, contents)

Program

# import yagmail module.
import yagmail

# connect to smtp server.
yag_smtp_connection = yagmail.SMTP( user="sender@gmail.com", password="senders_password", host='smtp.gmail.com')

# email subject
subject = 'Hello from THE BHUTAN IO'

# email content with the attached file path.
contents = ['Hello tom this is Sonam trying to send mail to you!']

# send the email
yag_smtp_connection.send('reciever@gmail.com', subject, contents)

There are several other cool features of this API described in their Git repository.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top