Python Auto Send Mail Library Yagmail Example

Yagmail is a python library which can make sending email simple and easy. This article will show you examples about how to use yagmail to send emails to multiple receivers with multiple attachments, it also shows the difference between yagmail and general python sending email method.

1. General Method Of Sending Emails.

In past days, i use below method to implement automated mail functionality in Python.

# import python built-in smtplib module
import smtplib
# import email MIMEText and Header class
from email.mime.text import MIMEText
from email.header import Header

# specify the smtp server which is used to send the email out.
smtpserver = 'smtp.google.com'
# sender user email.
user = '[email protected]'
# sender password
password = 'abc'
# sender email address.
from_addr = '[email protected]'
# receiver email address.
to_addr = '[email protected]'
# email subject
subject = 'Hello from roichard'

# create a MIMEText object with email html content.
msg = MIMEText('<html><h1>Hello tom!</h1></html>','html','utf-8')
# set email subject header
msg['Subject'] = Header(subject, 'utf-8')


# create a SMTP server instance.
smtp = smtplib.SMTP()
# connect to the provided smtp server.
smtp.connect(smtpserver)
# login to smtp server with provided username and password.
smtp.login(user, password)
# send the email 
smtp.sendmail(from_addr, to_addr, msg.as_string())
# quit them smtp server connection.
smtp.quit()

2. Send Email Use Yagmail.

Yagmail can make it more simple to achieve automatic mail function.

2.1 Install Yagmail.

Open a terminal and run below pip command to install yagmail first.

pip install yagmail

2.2 Yagmail Send Email Example.

# import yagmail module.
import yagmail

# connect to smtp server.
yag_smtp_connection = yagmail.SMTP( user="[email protected]", password="abc", host='smtp.gmail.com')

# email subject
subject = 'Hello from richard'

# email content with attached file path.
contents = ['Hello tom this is richard speaking', 'An image file is attached.', '/local/path/python.png']

# send the email
yag_smtp_connection.send('[email protected]', subject, contents)

2.3 Yagmail Send Email To Multiple Receivers.

Add multiple receivers email address in a python list.

yag.send(['[email protected]','[email protected]','[email protected]'], subject, contents)

2.4 Yagmail Send Email With Multiple Attachments.

Add multiple attachment files in a python list.

yag.send(['[email protected]','[email protected]'], 'Email with multiple attachments', contents, ["c://readme.txt","c://python.jpg"])