Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


Sending an e-mail message


The smtplib module supplies us with an SMTP class, which can be initialized by an
SMTP server socket. Upon successful initialization, this will give us an SMTP session
object. The SMTP client will establish a proper SMTP session with the server. This
can be done by using the ehlo() method for an SMTP session object. The actual
message sending will be done by applying the sendmail() method to the SMTP
session. So, a typical SMTP session will look like the following:


session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.sendmail(sender, recipient, msg.as_string())
session.quit()

In our example SMTP client script, we have made use of Google's free Gmail service.
If you have a Gmail account, then you can send an e-mail from a Python script to
that account by using SMTP. Your e-mail may get blocked initially, as Gmail may
detect that it had been sent from a less secure e-mail client. You can change your
Gmail account settings and enable your account to send/receive e-mails from less
secure e-mail clients. You can learn more about sending e-mail from an app on
the Google website, which can be found at https://support.google.com/a/
answer/176600?hl=en.


If you don't have a Gmail account, then you can use a local SMTP server setup in
a typical Linux box and run this script. The following code shows how to send an
e-mail through a public SMTP server:


#!/usr/bin/env python3
# Listing 1 – First email client
import smtplib

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

SMTP_SERVER = 'aspmx.l.google.com'
SMTP_PORT = 25

def send_email(sender, recipient):
""" Send email message """
msg = MIMEMultipart()
Free download pdf