Python Program to Send Emails Using Yagmail

Sending mail 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 yagmailCode language: JavaScript (javascript)
  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')Code language: PHP (php)
  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!']
Code language: PHP (php)
  1. And send the mail to your receiver.
yag_smtp_connection.send('reciever@gmail.com', subject, contents)
Code language: JavaScript (javascript)

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)Code language: PHP (php)

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

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top