Change language

Send email with attachment from your Gmail account using Python

| | | |

Steps to send mail with attachments from your Gmail account:

  1. To add an attachment, you need to import:
    • smtplib import
    • from email.mime.multipart import MIMEMultipart
    • from email.mime.text import MIMEText
    • from email.mime.base import MIMEBase
    • from encoders email import

    Here are some libraries that will make our job simple. These are native libraries and you don’t need to import any external library to do this.

  2. First, create a MIMEMultipart instance, namely "msg" to start.
  3. Specify the sender’s email ID, recipient’s email ID and subject in the From, To, and Subject keys of the generated msg instance.
  4. On a line, write the body of the message you want to send, namely the body. Now attach the body with the msg instance using the attach function.
  5. Open the file you want to attach in "rb" mode. Then create a MIMEBase instance with two parameters. The first — this is _maintype and the other is — _subtype. It is the base class for all MIME-specific Message subclasses. 
    Please note that "_maintype" is the primary Content-Type (such as text or image), and "_subtype" is the secondary type of Content-Type (such as plain or gif or other media).
  6. set_payload is used to change the payload of the encoded form. Encode it in encode_base64. Finally, attach the file with the MIMEMultipart-generated msg instance.

After completing these steps, follow the instructions in in the previous article, to create a session, secure and authenticate it, and then log off the session after sending mail.

# Python code to illustrate Sending mail with attachments
# from your Gmail account

 
# libraries to import

import smtplib

from email.mime.multipart import MIMEMultipart

from   email.mime.text import MIMEText

from email.mime.base import MIMEBase

from email import encoders

 

fromaddr = "EMAIL address of the sender"

toaddr = " EMAIL address of the receiver "

 
# MIMEMultipart instance

msg = MIMEMultipart ()

 
  # store senders email address

msg [ ’From’ ] = fromaddr

 
# store the recipient’s email address

msg [ ’To’ ] = toaddr

 
# item storage

msg [ ’Subject’ ] = "Subject of the Mail"

 
# string for storing the message body

body = " Body_of_the_mail "

  
# attach body to msg instance

msg.attach (MIMEText (body, ’plain’ ))

  
# open file for submission

filename = " File_name_with_extension "

attachment = open ( "Path of the file" , "rb" )

 
# MIMEBase instance named p

p = MIMEBase ( ’application’ , ’octet-stream’ )

  
# To change the payload into encoded form
p.set_payload ((attachment) .read ())

 
# base64 encoded
encoders.encode_base64 (p)

 

p.add_header ( ’Content-Disposition’ , " attachment; filename =% s " % filename)

  
# attach an instance & # 39; p & # 39; to an instance & # 39; msg & # 39;
msg.attach (p)

 
# creates a session SMTP

s = smtplib.SMTP ( ’smtp.gmail.com’ , 587 )

 
# launching TLS for security
s.starttls ()

 
# Authentication

s.login (fromaddr, "Password_of_the_sender" )

 
# Converts a multipart message to a string

text = msg.as_string ()

 
# sending mail
s.sendmail (fromaddr, toaddr, text)

 
# terminating the session
s.quit ()


Important points:

  • You can use loops to send emails to multiple people.
  • This code is simple to implement. But this won’t work if you’ve enabled 2-Step Verification on your Gmail account. You must first turn off two-step verification.
  • By using this method, Gmail will always put your mail in the main section and sent emails will not be spam.

This article is provided by Rishabh Bansal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically