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 = ''
# sender user email.
user = ''
# sender password
password = 'abc'
# sender email address.
from_addr = ''
# receiver email address.
to_addr = ''
# 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.
# 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.

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="", password="abc", host='')

# 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('', subject, contents)

2.3 Yagmail Send Email To Multiple Receivers.

Add multiple receivers email address in a python list.

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

2.4 Yagmail Send Email With Multiple Attachments.

Add multiple attachment files in a python list.

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

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.