Send emails using Python

Gmail GUI

Gmail API

This is a program written in Python using which you can send an email with multiple attachments(any kind) to multiple recipients.
I have used libraries like smtplib, email, MIME, etc. The code proceeds by making an SMTP server. The libraries you might need to import.

import smtplib
import email
import os
from email.MIMEMultipart import MIMEMultipart
from email.Utils import COMMASPACE
from email.MIMEBase import MIMEBase
from email.parser import Parser
from email.MIMEImage import MIMEImage
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
import mimetypes

Create an SMTP server. Connect it to the host.
Identify yourself to the server. >> SMTP.ehlo()
Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted.
Log in on the server.
more about smtplib : smtplib-docs

server = smtplib.SMTP()
server.connect('host',port) # for eg. host = '', port = 587
server.login('user', 'password')

SMTP server has been created and authorized for data transfer.
Create an email message with attachments. This part is here is a bit tricky and uses email library.
Get the required input from the user.

fromaddr = raw_input('Send mail by the name of: ')
tolist = raw_input('To: ').split()
sub = raw_input('Subject: ')

Create the message msg which is an instance of email.mime.multipart.MIMEMultipart.
msg is like a dictionary object. It stores the content corresponding to keys.

msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = email.Utils.COMMASPACE.join(tolist)
msg['Subject'] = sub
msg.attach(MIMEText(raw_input('Body: ')))
msg.attach(MIMEText('\nsent via python', 'plain')) # just a way to say.. Ha! I use Python.

For more information about MIMEBase visit email.mime
So, now your email is ready but does not contain any attachments. To attach files, we need to use MIME library.
We open the file for reading in binary form. We find the content type and encoding type of the file using mimetypes.

    filename = raw_input('File name: ')
    f = open(filename,'rb')
    ctype, encoding = mimetypes.guess_type(filename)

    if ctype is None or encoding is not None:
      ctype = 'application/octet-stream'

According to the type of the file, we use corresponding MIMEtype to encode the data of the file and save it in part which we would attach in msg. If subtype is other than ‘text’,’image’,’audio’, we encode the file with MIMEBase and attach the part as payload of msg

      maintype, subtype = ctype.split('/', 1)
      if maintype == 'text':
        part = MIMEText(, _subtype=subtype)
      elif maintype == 'image':
        part = MIMEImage(, _subtype=subtype)
      elif maintype == 'audio':
        part = MIMEAudio(, _subtype=subtype)
        part = MIMEBase(maintype, subtype)
      part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))

email is ready. It just needs to be sent.


So this is a small example of how to send emails using smtplib, email, MIMEBase from Python!

For complete code (including receiving emails) : Gmail API
For Gmail application GUI : Gmail GUI

P.S. It feels good to send emails via Python!

One thought on “Send emails using Python

  1. That is a great blog you have got there. I tried this out and it does work in my personal computer connected directly to the internet, but when I try this in my office where the system is connected through a proxy, it just doesn’t work, it gives me an error here,
    server.connect(‘host’,port) # for eg. host = ‘’, port = 587
    is there anyway you can help me with this?

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s