Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


Sending e-mail attachments


In the previous section, we have seen how plain text messages can be sent by using
the SMTP protocol. In this section, let us explore how to send attachments through
e-mail messages. We can use our second example, in which we have sent an e-mail
by using TLS, for this. While composing the e-mail message, in addition to adding a
plain text message, include the additional attachment field.


In this example, we can use the MIMEImage type for the email.mime.image sub-
module. A GIF type of image will be attached to the e-mail message. It is assumed
that a GIF image can be found anywhere in the file system path. This file path is
generally taken on the basis of the user input.


The following example shows how to send an attachment along with your
e-mail message:


#!/usr/bin/env python3

import os
import getpass
import re
import sys
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):
""" Sends email message """
msg = MIMEMultipart()
msg['To'] = recipient
msg['From'] = sender
subject = input('Enter your email subject: ')
msg['Subject'] = subject
message = input('Enter your email message. Press Enter when
finished. ')
Free download pdf