How to Send an Email With Yagmail

On July 07, 2024
6min read
Yevhenii Odyntsov Content @Mailtrap

Yagmail is a simple GMAIL/SMTP client that is created to remove the hassle out of sending emails. With the Python library, you can write a few lines of code to include email sending capabilities to your application and sidestep using the cumbersome traditional approaches. In this tutorial, we’re going to demonstrate how to use Yagmail for sending emails.

So, let’s get started….

Project Setup

Let’s begin by setting up the following requirements for this Yagmail in Python tutorial:

  • Gmail account: Since Yagmail is designed to interact with Gmail accounts, we’ll set up an account for this project. Next, on the account’s security settings, we’ll turn on the Allow less secure apps option—this will allow our app to interact with Gmail without any issues. Note that this makes your account vulnerable to unauthorized access. So, if you want to enforce the security of your Gmail account, you can use the OAuth2 authorization framework to get the access rights.
  • Yagmail: For setting up Yagmail on our development environment, we’ll simply run the following command:
pip install yagmail

Then, we’re ready to go!

How to Send an Email with Yagmail

Here is the code for sending an email using Yagmail:

#importing the Yagmail library
import yagmail
try:
    #initializing the server connection
    yag = yagmail.SMTP(user='my_username@gmail.com', password='mypassword')
    #sending the email
    yag.send(to='recipient_username@gmail.com', subject='Testing Yagmail', contents='Hurray, it worked!')
    print("Email sent successfully")
except:
    print("Error, email was not sent")

It’s that simple!

Let’s explain what is happening in the code above:

  • We started by importing the Yagmail Python library into our project.
  • We created a yagmail.SMTP instance to initialize the server connection.
  • For authentication, we specified the address and the password of the Gmail account we created. A safer way of implementing authentication is to use OAuth2 credentials, as the rights of tokens can easily be revoked. It can be done by simply passing the oauth2_file  to yagmail.SMTP. 

Here is an example:

yag = yagmail.SMTP("my_username@gmail.com", oauth2_file="~/oauth2_creds.json")
  • Finally, we invoked the Yagmail’s send() function to specify the details of our email message. Although the parameters of the function are optional, we used the three keyword arguments to specify the recipient’s email address, the email’s subject, and the email’s body, respectively. 
  • We also wrapped the entire code in a try…except block to handle any errors, such as a wrong password.

If we run the code and check our Gmail account, we find the message in the inbox:

That’s the simple way for Yagmail usage in sending emails.

Sending Email with Multiple Attachments in Yagmail

To send an email with an attachment in Yagmail, simply specify the attachments keyword argument as a parameter in the send() function and provide the attachment’s absolute path.

Here is an example:

#importing the Yagmail library
import yagmail
try:
    #initializing the server connection
    yag = yagmail.SMTP(user=''my_username@gmail.com', password='password')
    #sending the email
    yag.send(to=' recipient_username@gmail.com', subject='Sending Attachment', contents='Please find the image attached', attachments='Desktop/File 1/image1.png')
    print("Email sent successfully")
except:
    print("Error, email was not sent")

If we run the code and check our Gmail account, we find the attachment in the inbox:

C:\Users\OPIDI\Downloads\szoter_annotated_image(1).jpeg

To send an email with multiple attachments, simply pass a list of the attachments to the attachments argument.

Here is an example:

yag.send(to='user1@gmail.com', subject='Sending Attachments', contents='Please find the images attached', attachments=['Desktop/File 1/image1.png','Desktop/File 1/gantt2.png','Desktop/File 1/gantt3.png'])

If we check our Gmail account, we find the attachments:

C:\Users\OPIDI\Downloads\szoter_annotated_image(2).jpeg

Sending Emails to Multiple Recipients

Yagmail in Python makes it easy to send an email to a group of people. To do that, simply pass a list of email addresses to the to argument.

Here is an example:

  yag.send(to=['user1@gmail.com', 'user2@gmail.com', 'user3@gmail.com'], subject='Greetings...', contents='How are you?')

Here is the output:

C:\Users\OPIDI\Downloads\szoter_annotated_image(3).jpeg

Sending Emails with CC and BCC Fields

To send an email with CC (carbon Copy) field and BCC (Blind Carbon Copy) field, simply specify cc and bcc keyword arguments as parameters in the send() function.

Here is a Yagmail usage example:

yag.send(to='user1@gmail.com', cc='user2@gmail.com', bcc='user3@gmail.com', subject='Greetings...', contents='How are you?')

Let’s see the results in our Gmail inbox:

C:\Users\OPIDI\Downloads\szoter_annotated_image(4).jpeg

How to Send an HTML Email

Furthermore, setting up Yagmail to send an HTML email message is easy; in the contents argument of Yagmail’s send() function, we can pass a valid HTML and the message will be formatted according to the provided HTML syntax.

Here is an example:

yag.send(to='user1@gmail.com', subject='Greetings...', contents='<h1>How are you?</h1>')

Here is how the message appears in our Gmail inbox:

C:\Users\OPIDI\Downloads\szoter_annotated_image(8).jpeg

How to Test Emails with Mailtrap Email Sandbox and Yagmail

The emails you send with Yagmail, or any other technology, as a matter of fact, need to be tested before they are sent out. This way, you can make sure that your emails will look as you intended once they reach recipient inboxes, that you aren’t going to trigger any spam filters with your email content, and that your sender IP/domain is not present on any blacklists.

For inspecting and debugging emails in a straightforward and secure way, we use Mailtrap Email Sandbox.

This tool has the features to automate test flows and scenarios. It can also capture SMTP traffic from staging and dev environments, so you can’t spam recipients with testing emails.

 With the tool, devs get to:

  • Create multiple virtual inboxes for different projects and project stages 
  • Validate email HTML/CSS code
  • Check email content spam score
  • Preview emails on different screen sizes
  • Check common blacklists for the presence of their IP/domain 
  • View original values of headers and SMTP transaction details
  • Forward messages to whitelisted recipients

On top of that, Mailtrap includes a 5-minute setup process and can help preserve domain reputation through the use of virtual inboxes, making it a testing tool worth considering.

To start testing emails with Mailtrap Email Sandbox, an active Mailtrap account is required. Once the account is set up, testing emails can be sent using the below code with your credentials in it: 

#importing the Yagmail library
import yagmail
try:
 #initializing the server connection
  yag = yagmail.SMTP(
  #required to bypass email format validation
  user={'INSERT MAILTRAP USERNAME':''}, #Mailtrap username
  soft_email_validation=False,
  password='INSERT MAILTRAP PASSWORD', #Mailtrap password
  host='smtp.mailtrap.io',
  smtp_starttls=True,
  smtp_ssl=False
 )
 #sending the email
 yag.send(to='user1@gmail.com', subject='Mailtrap and Yagmail', contents='The testing worked!')
 print("Email sent successfully")
except:
 print("Error, email was not sent")

The email should land in your virtual inbox shortly after running the code. After that, you are free to inspect and debug using Mailtrap Email Sandbox features.

Sending Emails in Python Without Using Yagmail

One drawback of Yagmail is that it can be used only with Gmail email addresses. So, if you are looking to send emails in Python without the use of Yagmail, we advise you to check out our in-depth tutorial on the topic.

In the tutorial, we mention the usage of third-party sending solutions. More specifically, Mailtrap Email API.

Mailtrap Email API is an end-to-end sending solution that can deliver emails from any application using its email API or SMTP service. With it, you reach recipient inboxes and monitor your deliverability with dashboards, logs, and weekly reports.

The Mailtrap Email API dashboards are designed to give a snapshot of your email deliverability by showing you vital stats for a selected period along with a percentile comparison to the previous period.

The email logs show all the emails sent from your account and their delivery history. 

Additionally, the weekly reports give a detailed preview of your stats, including opens, clicks, bounces, unsubscribes, and spam reports.

Sending with Mailtrap Email API can be initiated after you have created a Mailtrap account, added and verified a domain, and pasted the email sending code snippet into your project. 

For Python (and other programming languages), you can find the snippet under Sending Domains-> API and SMTP.

Take the snippet you are provided with, add it to your Python project, run it, and start sending emails without any issues.

In the rare case any sending issues arise, you can count on Mailtrap Email API weekly deliverability alerts to notify you in time. Just don’t forget to enable them beforehand!

Wrapping Up

Gmail is a versatile email service that is widely used across the world. With Yagmail, you can simplify the tasks of sending emails to Gmail users and take the functionalities of your application to the next level. 

Of course, in this tutorial, we just scratched the surface of what is possible with Yagmail usage. If you want to see more usage examples, you can check its documentation.

If, on the other hand,  you now think that Yagmail is not for you, you can try sending (and testing) your emails in Python with the Mailtrap Email Delivery platform instead.

Article by Yevhenii Odyntsov Content @Mailtrap

I’ve been writing email-oriented content for over 4 years now and I’m still finding new and exciting topics and technologies about email infrastructure and deliverability, email sending and testing, and much more. I hope you’ll enjoy it!