Python | Send an Email with Multiple Attachments

Send an Email with Multiple Attachments


Today's Agenda

In this post, we will learn how to setup a Python function to send Emails with attachment (optional). We will setup an SMTP server that could send Emails to the clients whenever triggered.

Prerequisite

This post has been prepared for the audience who : 
  1. Have an email account to send the emails.
  2. Have Python 3 installed over their systems that can be used to run the code. Check for python version using: python --version
  3. And finally, who are eager to learn and try such useful example.

Let's get started

In this post, we will setup an SMTP server to send Emails to the users with multiple attachments. We will use Python Version: 3.6 (or higher will be compatible). Follow the code below for the above use case and do read the comments to get crux for each block of code.


# Import all the required libraries

import smtplib

import json
import os
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

import string

import base64
from email.encoders import encode_base64


# function to send the email
def sendEmail():

    # initialise variables
    username = "SENDER'S_EMAIL_ID"
    password = "SENDER'S_EMAIL_PASSWORD"
    host = "smtp.gmail.com"
    port = "587"
    sender_email ="SENDER'S_EMAIL_ID"
    new = "RECEIVER'S_EMAIL_ID1, RECEIVER'S_EMAIL_ID2, RECEIVER'S_EMAIL_ID3"

    receiver_email = new.split(",")


    message = MIMEMultipart("alternative")

    message["Subject"] = "Application for a Coffee date!"

    message["From"] = "SENDER'S_EMAIL_ID"

    furl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
    file = requests.get(furl, allow_redirects=True)
    attachfile = open('/tmp/attachment', 'wb')
    attachfile.write(file.content)
    attachfile.close()
       
    name_list = furl.split("/")
    name = name_list[-1]
       
    attach_file=MIMEApplication(open("/tmp/attachment","rb").read())
    attach_file.add_header('Content-Disposition', 'attachment', filename=name)
    message.attach(attach_file)

    html = "Reply with the place and time."
    part2 = MIMEText(html, "html")
    message.attach(part2)
   
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.ehlo()
        server.starttls()
        server.login(username, password)
        server.sendmail(
          sender_email, receiver_email, message.as_string()
        )

    print('Sent')
    return {
        'statusCode': 200,
        'body': json.dumps('sent')
    }


# function call

if __name__ == "__main__" sendEmail()

       
 






Comments