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. ') part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) # attach an image in the current directory filename = input('Enter the file name of a GIF image: ') path = os.path.join(os.getcwd(), filename) if os.path.exists(path): img = MIMEImage(open(path, 'rb').read(), _subtype="gif") img.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(img) # create smtp session session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo # 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)
If you run the preceding script, then it will ask the usual, that is, the e-mail sender, the recipient, the user credentials, and the location of the image file.
$ python3 smtp_mail_sender_mime.py Enter sender email address: [email protected] Enter recipeint email address: [email protected] Enter your email subject: Test email with attachment Enter your email message. Press Enter when finished. This is a test email with atachment. Enter the file name of a GIF image: image.gif You email is sent to [email protected].