In previous article you have learnt How To Send Email Use Gmail Free SMTP Service, but as a python developer, you also want to send email through gmail free SMTP server in python source code. This article will tell you how to implement it and the issues solution during the process.
There are two python libraries that you can use to send email through gmail SMTP server in python code. We will give you both library examples.
- Python built-in smtplib module : This module is installed with python by default.
- Yagmail module : This is a gmail client library, you need to install it before using it.
Before you copy and run below source code, you need do following preparations, otherwise you may encounter errors.
- Turn on google account Allow Less Secure Apps option. Because gmail do not allow access from source code by default, gmail treat your python source code as Less Secure App. Please refer article How Do I Enable Less Secure Apps On Gmail. If you do not turn it on, you may encounter below error messages like TimeoutError: [Errno 110] Connection timed out.
- Display unlock captcha for your gmail account. This is because gmail may use captcha feature to block spam access when you run the source code, but below code can not process the captcha.
Click the Continue button in the Allow access to your Google account web page otherwise when you run the example code, you may encounter error message like smtplib.SMTPAuthenticationError: (535, b’5.7.8 Username and Password not accepted.
- 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’.
- If you meet any error when you run below example to login to your gmail account, you can refer the google gmail account cannot sign in trouble shooting page to find the answer.
1. Use Python Smtplib Module.
''' Created on Dec 31, 2018 @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()
2. Use Python Yagmail Module.
2.1 Install Yagmail.
First you need to install python yagmail module follow below steps.
- Open a terminal and run
$ pip3 install yagmailcommand.
- Then run
$ pip3 show yagmailto 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:
- 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 How To Add Python Module Library In Eclipse PyDev. Now you can develop and debug yagmail code in the eclipse pydev project,
- If you find the eclipse pydev ide can not import keyring module, you should first run
$ pip3 install keyringin a terminal to install it, then run
$ pip3 show keyringto get keyring install folder and add the folder in eclipse pydev project PyDev-PYTHONPATH —> External Libraries as above to make keyring module importable.
2.2 Use Yagmail To Send Email Through Gmail Smtp Server In Python Source Code.
''' Created on Dec 31, 2018 @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()