Learning Python Network Programming

(Sean Pound) #1
Chapter 4

reply: b'250 2.0.0 OK 1414233177 hg2si4622244wib.38 - gsmtp\r\n'


reply: retcode (250); Msg: b'2.0.0 OK 1414233177 hg2si4622244wib.38 -
gsmtp'


data: (250, b'2.0.0 OK 1414233177 hg2si4622244wib.38 - gsmtp')


You email is sent to [email protected].


send: 'quit\r\n'


reply: b'221 2.0.0 closing connection hg2si4622244wib.38 - gsmtp\r\n'


reply: retcode (221); Msg: b'2.0.0 closing connection
hg2si4622244wib.38 - gsmtp'


This is interesting because the message has been sent through a public SMTP server
in a step-by-step fashion.


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
Free download pdf