Send email with file attachment in Python with SMTP

Hey there everyone, Today we are going to learn how to send a file or attachment to an email using Python. It’s one of the coolest stuff that can be done using some Python libraries. We would be using “smtplib” which is included in Python along with some external libraries to achieve this.

So, let’s get started.

Import libraries to send file attachment with email

We will import “smtplib” for creating an instance of the Simple Mail Transfer Protocol that would allow us to send our mail.

If we were to send a mail without any file, this would have been enough, you may refer this Send Email using SMTP in Python. But, as our mail contains a file, we will have to include some other libraries as mentioned below:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

Note

Please take care of the following points for the proper functioning of the given code without any interruption:

  • visit “https://myaccount.google.com/lesssecureapps” and turn it ON.
  • The file to be sent and your python code should be present in the same folder.
  • We are sending mail using Gmail having port number 587, some other website will have a different port number.

Now, we will briefly discuss all the steps of our python program:

  • Storing the sender’s and receiver’s email addresses
    sender_email = "[email protected]"
    receiver_email = "[email protected]"
  • Creating an instance of MIMEMultipart
    message = MIMEMultipart()
  • Assigning the sender_email, receiver_email, and subject of our mail
    message["From"] = sender_email
    message['To'] = receiver_email
    message['Subject'] = "sending mail using python"
  • As we have to mail the file “doc.txt”,  it’s opened in read-only in binary format mode
    file = "doc.txt"
    attachment = open(file,'rb')

    If your file is not present in the folder containing your Python program you will have to put your exact file location
    example: file = “file_name”
    attachment = open(“file location”,’rb’)

  • Creating an instance of MIMEBase
    obj = MIMEBase('application','octet-stream')
  • In simple terms, the payload is the file that we are mailing and here the payload is being encoded
    obj.set_payload((attachment).read())
    encoders.encode_base64(obj)
    obj.add_header('Content-Disposition',"attachment; filename= "+file)
  • Attaching the ‘obj’ to our message
    message.attach(obj)
  • Converting the message into a string just like given below:
    my_message = message.as_string()
  • SMTP session is created and TLS(Transport Layer Security) is started, TLS used for securing the connection, and the correct password should be provided for the session to start and proper authentication
    email_session = smtplib.SMTP('smtp.gmail.com',587)
    email_session.starttls()
    email_session.login(sender_email,'password')

    password -> your email id’s password

  • Sending the mail
    email_session.sendmail(sender_email,receiver_email,my_message)
  • Terminating the session
    email_session.quit()
  • Below is given our complete Python program to sent file with the email:
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
    
    sender_email = "[email protected]"
    receiver_email = "[email protected]"
    
    message = MIMEMultipart()
    
    message["From"] = sender_email
    message['To'] = receiver_email
    message['Subject'] = "sending mail using python"
    
    file = "doc.txt"
    attachment = open(file,'rb')
    
    obj = MIMEBase('application','octet-stream')
    
    obj.set_payload((attachment).read())
    encoders.encode_base64(obj)
    obj.add_header('Content-Disposition',"attachment; filename= "+file)
    
    message.attach(obj)
    
    my_message = message.as_string()
    email_session = smtplib.SMTP('smtp.gmail.com',587)
    email_session.starttls()
    email_session.login(sender_email,'password')
    
    email_session.sendmail(sender_email,receiver_email,my_message)
    email_session.quit()
    print("YOUR MAIL HAS BEEN SENT SUCCESSFULLY")

    After the successful execution of this code, your mail containing the file will be sent to the receiver and “YOUR MAIL HAS BEEN SENT SUCCESSFULLY” printed on your terminal.

    YOUR MAIL HAS BEEN SENT SUCCESSFULLY

Also, read: Send Email using SMTP in Python

So we are successfully able to send our attachment with email in Python using the SMTP.

Leave a Reply

Your email address will not be published. Required fields are marked *