Establishing a connection with a Gmail SMTP server

It is possible to take advantage of the free Gmail SMTP server to send emails. It can be the definitive solution for those who cannot use the SMTP server that's provided by their ISP or their host, as well as those who experience several problems with sending emails. In this section, you will learn how to use the free Gmail SMTP server.

To establish a connection with smtp.gmail.com, we can use the following instructions:

mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login("[email protected]","password")

Basically, we indicate smtp.gmail.com as the mail server name and the connection as port 587. Then, we establish the starttls() protocol, sending an ehlo() message beforehand to accept it. Finally, we enter the session with [email protected] and the corresponding password, once again sending an ehlo() message beforehand.

You can see all of these features in the smtp_login_tls.py file:

#!/usr/bin/env python3

import sys, smtplib, socket

# this invokes the secure SMTP protocol (port 465, uses SSL)
from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText

try:
msg = MIMEText("Test message", 'plain')
msg['Subject']= "Sent from Python"
msg['From'] = "[email protected]"

In the previous code block we import necessary packages and define our message object using MIMEText class.In the next code block we create smtp session and if the server it supports SSL encryption,establish a secure connection with the server.

    # create smtp session
smtp = smtplib.SMTP("smtp.gmail.com", 587)
#debug active
smtp.set_debuglevel(True)
# identify ourselves to smtp gmail client
smtp.ehlo()

# Check if we can encrypt this session
if smtp.has_extn('STARTTLS'):
# secure our email with tls encryption
smtp.starttls()
# re-identify ourselves as an encrypted connection
smtp.ehlo()

Once we have created our SMTP session and checked whether we can encrypt this session, we can use the login method for authenticating our user credentials and send an email with the sendmail method:

    try:
smtp.login("[email protected]", "password")
except smtplib.SMTPException as e:
print("Authentication failed:", e)
sys.exit(1)

try:
smtp.sendmail('[email protected]', ['[email protected]'], msg.as_string())
except (socket.gaierror, socket.error, socket.herror,smtplib.SMTPException) as e
print(e)
sys.exit(1)
finally:
smtp.quit()

except (socket.gaierror, socket.error, socket.herror,smtplib.SMTPException) as e:
print(e)
sys.exit(1)

In the next section, we are going to review the configuration for sending emails with the Gmail SMTP service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset