Sending e-mails securely with TLS

TLS protocol is a successor of SSL or Secure Socket Layer. This ensures that the communication between the client and the server is secure. This is done by sending the message in an encrypted format so that unauthorized people cannot see the message. It is not difficult to use TLS with smtplib. After you create an SMTP session object, you need to call the starttls() method. Before sending an e-mail, you need to login to the server by using the SMTP server credentials.

Here is an example for the second e-mail client:

#!/usr/bin/env python3
# Listing 2
import getpass
import smtplib

from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587 # ssl port 465, tls port 587

def send_email(sender, recipient):
    """ Send email message """
    msg = MIMEMultipart()
    msg['To'] = recipient
    msg['From'] = sender
    msg['Subject'] = input('Enter your email subject: ')
    message = input('Enter your email message. Press Enter when finished. ')
    part = MIMEText('text', "plain")
    part.set_payload(message)
    msg.attach(part)
    # create smtp session
    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    session.set_debuglevel(1)
    session.ehlo()
    session.starttls()
    session.ehlo
    password = getpass.getpass(prompt="Enter you email password: ") 
    # login to server
    session.login(sender, password)
    # send mail
    session.sendmail(sender, recipient, msg.as_string())
    print("You email is sent to {0}.".format(recipient))
    session.quit()

if __name__ == '__main__':
    sender = input("Enter sender email address: ")
    recipient = input("Enter recipeint email address: ")
    send_email(sender, recipient)

The preceding code is similar to our first example, except for the authentication to the server. In this case, the SMTP user is authenticated against the server. If we run the script after turning on the SMTP debugging, then we would be seeing an output similar to the following:

$ python3 smtp_mail_sender_tls.py 
Enter sender email address: [email protected]
Enter recipeint email address: [email protected]
Enter your email subject: Test email
Enter your email message. Press Enter when finished. This is a test email that can be ignored.

After the user input, communication with the server will begin. It will start by the ehlo() method. In response to this command, the SMTP server will send a few response lines with the return code 250. This response will include the features supported by the server.

The summary of these responses will indicate that the server is ready to proceed with the client, as shown in the following:

send: 'ehlo debian6box.localdomain.loc
'
reply: b'250-mx.google.com at your service, [77.233.155.107]
'
reply: b'250-SIZE 35882577
'
reply: b'250-8BITMIME
'
reply: b'250-STARTTLS
'
reply: b'250-ENHANCEDSTATUSCODES
'
reply: b'250-PIPELINING
'
reply: b'250-CHUNKING
'
reply: b'250 SMTPUTF8
'
reply: retcode (250); Msg: b'mx.google.com at your service, [77.233.155.107]
SIZE 35882577
8BITMIME
STARTTLS
ENHANCEDSTATUSCODES
PIPELINING nCHUNKING
SMTPUTF8'

After the initial command, the client will use the starttls() method to upgrade the connection to TLS, as shown here:

send: 'STARTTLS
'
reply: b'220 2.0.0 Ready to start TLS
'
reply: retcode (220); Msg: b'2.0.0 Ready to start TLS'
Enter you email password: 
send: 'ehlo debian6box.localdomain.loc
'
reply: b'250-mx.google.com at your service, [77.233.155.107]
'
reply: b'250-SIZE 35882577
'
reply: b'250-8BITMIME
'
reply: b'250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
'
reply: b'250-ENHANCEDSTATUSCODES
'
reply: b'250-PIPELINING
'
reply: b'250-CHUNKING
'
reply: b'250 SMTPUTF8
'
reply: retcode (250); Msg: b'mx.google.com at your service, [77.233.155.107]
SIZE 35882577
8BITMIME
AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
ENHANCEDSTATUSCODES
PIPELINING
CHUNKING
SMTPUTF8'

In the authentication phase, the authentication data is sent by the client-side script with the help of the login() method. Note that the authentication token is a base-64 encoded string and the username and password are separated by a null byte. There other supported authentication protocols exists for the sophisticated clients. The following is the example of authentication token:

send: 'AUTH PLAIN A...dvXXDDCCD.......sscdsvsdvsfd...12344555
'
reply: b'235 2.7.0 Accepted
'
reply: retcode (235); Msg: b'2.7.0 Accepted'

After the client is authenticated, it can send e-mail messages by using the sendmail() method. Three arguments are passed to this method, sender, recipient, and the message. The sample output is shown here:

send: 'mail FROM:<[email protected]> size=360
'
reply: b'250 2.1.0 OK xw9sm8487512wjc.24 - gsmtp
'
reply: retcode (250); Msg: b'2.1.0 OK xw9sm8487512wjc.24 - gsmtp'
send: 'rcpt TO:<[email protected]>
'
reply: b'250 2.1.5 OK xw9sm8487512wjc.24 - gsmtp
'
reply: retcode (250); Msg: b'2.1.5 OK xw9sm8487512wjc.24 - gsmtp'
send: 'data
'
reply: b'354  Go ahead xw9sm8487512wjc.24 - gsmtp
'
reply: retcode (354); Msg: b'Go ahead xw9sm8487512wjc.24 - gsmtp'
data: (354, b'Go ahead xw9sm8487512wjc.24 - gsmtp')
send: 'Content-Type: multipart/mixed; boundary="===============1501937935=="
MIME-Version: 1.0

To: <Output omitted>-===============1501937935==--
.
'
reply: b'250 2.0.0 OK 1414235750 xw9sm8487512wjc.24 - gsmtp
'
reply: retcode (250); Msg: b'2.0.0 OK 1414235750 xw9sm8487512wjc.24 - gsmtp'
data: (250, b'2.0.0 OK 1414235750 xw9sm8487512wjc.24 - gsmtp')
You email is sent to [email protected].
send: 'quit
'
reply: b'221 2.0.0 closing connection xw9sm8487512wjc.24 - gsmtp
'
reply: retcode (221); Msg: b'2.0.0 closing connection xw9sm8487512wjc.24 - gsmtp'
..................Content has been hidden....................

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