How To Send Email With Gmail As Provider Using Python

In the previous article, you have learned How To Send Emails Use Gmail Free SMTP Service, but as a python developer, you also want to send emails through Gmail free SMTP server in python source code. This article will tell you how to implement it and the solution to the issues during the process.

There are two python libraries that you can use to send email through the Gmail SMTP server in python code. We will give you both library examples.

  1. Python built-in smtplib module: This module is installed with python by default.
  2. Yagmail module: This is a Gmail client library, you need to install it before using it.

1. Preparations.

  1. Before you copy and run below source code, you need to do the following preparations, otherwise, you may encounter errors.
  2. Turn on the google account Allow Less Secure Apps option. Because Gmail does not allow access from source code by default, Gmail treats your python source code as Less Secure App. Please refer article How Do I Enable Less Secure Apps On Gmail. So if you do not turn it on, you may encounter the error messages like TimeoutError: [Errno 110] Connection timed out.
  3. It may also display unlock captcha for your Gmail account. This is because Gmail may use the captcha feature to block spam access when you run the source code, but the below code can not process the captcha.
  4. Click the Continue button in the Allow access to your Google account web page otherwise when you run the example code, you may encounter an error message like smtplib.SMTPAuthenticationError: (535, b’5.7.8 Username and Password not accepted.
  5. When you use Yagmail to implement send email through Gmail SMTP server function, create a .yagmail file in your home directory. And write your Gmail email address in this file. Otherwise you may encounter error message like FileNotFoundError: [Errno 2] No such file or directory: ‘/home/zhaosong/.yagmail’.
  6. If you meet any error when you run the below example to log in to your Gmail account, you can refer to the Google Gmail account cannot sign in troubleshooting page to find the answer.

2. Use Python Smtplib Module.

  1. Below is the python source code that demos how to use the python smtplib module.
    '''
    @author: zhaosong
    '''
    
    import smtplib
    import ssl
    from email.mime.text import MIMEText
    
    
    # gmail sender email address and password.
    from_addr = '[email protected]'
    from_addr_password = '12345678'
    # receiver email address.
    to_addr = '[email protected]'
        
    
    ''' This function will send email through gmail smtp server use python built-in smtplib library. '''
    def send_email_via_gmail_smtp_service_use_smtplib():
        # create MIMEText object which represent the email message.    
        msg = MIMEText('This email sent through gmail smtp service use python built-in smtplib.', 'plain', 'utf-8')
        # set email message from, to and subject attribute value.
        msg['From'] = from_addr
        msg['To'] = to_addr
        msg['Subject'] = 'Email sent through gmail smtp server.'
        
        # create a ssl context object because gmail need ssl access.
        ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)
        # start ssl encryption from very beginning.
        print('starting connect gmail smtp server with ssl.')
        # smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465, context=ctx)
        # create SMTP connection object.
        smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
        # start tls to make the connection secure.
        smtp_server.starttls(context=ctx)
        print('start login gmail smtp server.')
        smtp_server.login(from_addr, from_addr_password)
        print('start send message through gmail service.')
        smtp_server.send_message(msg, from_addr, to_addr)
        print('Send email by python smtplib module through gmail smtp service complete.')
    
    if __name__ == '__main__':
        send_email_via_gmail_smtp_service_use_smtplib()
    

3. Use Python Yagmail Module.

3.1 Install Yagmail.

  1. First, you need to install the python yagmail module follow the below steps.
  2. Open a terminal and run the command $ pip3 install yagmail.
  3. Then run $ pip3 show yagmail to list it’s installation information.
    Name: yagmail
    Version: 0.11.214
    Summary: Yet Another GMAIL client
    Home-page: https://github.com/kootenpv/yagmail
    Author: Pascal van Kooten
    Author-email: [email protected]
    License: MIT
    Location: /home/zhaosong/.local/lib/python3.6/site-packages
    Requires:
  4. If you use eclipse PyDev to develop the python example code, add the yagmail library saved directory path in your project PyDev – PYTHONPATH —> External Libraries like below. You can refer to How To Add Python Module Library In Eclipse PyDev. Now you can develop and debug yagmail code in the eclipse PyDev project,
  5. If you find the eclipse PyDev IDE can not import the keyring module, you should first run $ pip3 install keyring in a terminal to install it, then run $ pip3 show keyring to get keyring install folder and add the folder in eclipse PyDev project PyDev-PYTHONPATH —> External Libraries as above to make keyring module importable.

3.2 Use Yagmail To Send Email Through Gmail Smtp Server In Python Source Code.

  1. Below are python source code demos on how to use yagmail to send email through the Gmail SMTP server.
    '''
    @author: zhaosong
    '''
    
    import yagmail
    import keyring
    
    # gmail sender email address and password.
    from_addr = '[email protected]'
    from_addr_password = '12345678'
    # receiver email address.
    to_addr = '[email protected]'
        
    
    ''' This function will send the email through gmail smtp server use yagmail library. '''   
    def send_email_via_gmail_smtp_service_use_yagmail():
        
        # yagmail default keyring service name is yagmail.
        keyring_service_name = 'yagmail'
        
        # get gmail account password from the OS key chain database.
        password = keyring.get_password(keyring_service_name,from_addr)
        # if gmail password has been saved before.
        if(password != None):
            print(from_addr + " password stored in keyring is " + str(password))
            print('remove exist password in keyring')
            # remove the old password from os key chain and use the new one.
            keyring.delete_password(keyring_service_name, from_addr)
            
        ''' yagmail.register function will invoke keyring.set_password function 
            to save your gmail email address and password in the OS key chain to make 
            gmail account more secure. Because you do not need to write the password in python script every time,
            to demo how keyring behave we register the email address and password in this python script for each execution.
            '''
        yagmail.register(from_addr, from_addr_password)    
            
        ''' connect to smtp server. If you do not provide from_addr and from_addr_password value, it will through error FileNotFoundError: [Errno 2] No such file or directory: '/home/zhaosong/.yagmail'
            if you provide from_addr value only, it will prompt you to input the password. Then yagmail will invoke keyring module to save the email address and password in the os key chain database.
        '''
        yag_smtp_connection = yagmail.SMTP(from_addr, from_addr_password)
        
        # get the email password from os key chain database again after register.
        password = keyring.get_password(keyring_service_name,from_addr)
        
        print(from_addr + " new password stored in keyring is " + str(password))
        
        # email subject
        subject = 'Email send by yagmail'
        # email content with attached file path.
        contents = ['This email is sent by python yagmail.', 'An image file is attached.', '/home/zhaosong/WorkSpace/python-logo.png']
        
        # send the email
        print('start sending email to ' + to_addr)
        
        # send email is very simple. You do not need to create email message related object like MIMEText object.
        yag_smtp_connection.send(to_addr, subject, contents)
    
        print('Send email by python yagmail module through gmail smtp service complete.')
    
    
    if __name__ == '__main__':
        send_email_via_gmail_smtp_service_use_yagmail()
    

Reference

  1. Python Send Plain Text, Html Content, Attached Files, Embedded Images Email Example
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x