How to Use Gmail API in Python to Send a Mail?

Posted in /  

How to Use Gmail API in Python to Send a Mail?

Vinay Khatri
Last updated on May 22, 2024

    This Python tutorial discusses how to use Gmail API in Python to send mail. Gmail is one of the most popular email services.

    Owned by Google, many people use Gmail to send official and personal emails. It is used by everyone, ranging from professionals and businesses to students and children. As Gmail provides 2-step verification (2SV) to its users, hackers cannot easily hack the user account, and the details and mails remain safe.

    Although the 2-step verification of Gmail is a must option to activate, if 2SV is on for your Gmail account, you will find difficulties sending emails from the Python SMTP module. This is obvious because Gmail does not allow you to use any third-party software or package to log in to your account if 2SV is active. Although with the Python SMTP module, you can send emails using your Gmail account, you have to downgrade your Gmail security by deactivating the 2SV feature.

    So, is there any other option for sending emails with Gmail in Python without deactivating the 2-factor authentication? The answer is yes! It's all thanks to Gmail App Passwords API that allows you to send an email with Python without deactivating the 2SV feature and without even specifying the original password in the Python script.

    What is Gmail App Passwords?

    The Gmail App Passwords is an API that generates a 16-digit passcode for your non-google application and allows you to use that password to access your Google account. Moreover, you can only use Gmail App Passwords if you have enabled 2SV in your account.

    Here, in this Python tutorial, we will detail how to use Gmail API in Python to send a mail. We will also learn how to send attachments via Gmail using Python.

    How to Use Gmail API in Python to Send a Mail?

    Step 1: Create a Gmail Account

    This goes without saying. If you want to send an email using Gmail, then you first require a Gmail account. You can create a Gmail account by signing up here . For this tutorial, we have created a new Gmail account by the name . Here is what its inbox looks like:

    Step 2: Create a Gmail App Password

    Check this link to know how to create and use app passwords. Although the following screenshot details the steps of doing the aforementioned, it's recommended to open the link once to check for any updates in the process:

    a: Go to your Google Account

    b: Click on Security

    In the Security section, looks for App passwords and click on it to create a new app passcode.

    Note: Also, make sure that 2-Step Verification is on.

    c: Select Other Custom Name

    In the App passwords section, select Other (Custom Name) in the Select app option.

    d: Generate App

    Now generate an App by the name My App . The name My App is arbitrary; thus, you can choose any name of your liking.

    e: Copy the Generated App Password Note:

    Do not share the generated passcode with anyone!

    Once the password is created, copy it to your clipboard because we will be using it in our Python script to access the Gmail account.

    Note: Do not click on the Done button without copying the 16-character password, or else you will lose the password, and you have to delete the app and create a new one.

    f: All done with App password

    Once your app password is generated, you will see a similar screen to the one shown above. So now that we are done with the app password let's code in Python to send an email using the Gmail account.

    Note: You will also be receiving a confirmation email from Google after creating the App password.

    Step 3: Write Python Program to Send Email through Gmail

    #Example 1: python program to send Gmail emails with Python

    import smtplib
    from email.message import EmailMessage
    msg= EmailMessage()
    my_address =""    #sender address
    app_generated_password = "habebwgknjtopoxd"    # gmail generated password
    msg["Subject"] ="The Email Subject"   #email subject 
    msg["From"]= my_address      #sender address
    msg["To"] = ""     #reciver address
    msg.set_content("This is the body of the email")   #message body
    with smtplib.SMTP_SSL("", 465) as smtp:
        smtp.login(my_address,app_generated_password)    #login gmail account
        print("sending mail")
        smtp.send_message(msg)   #send message 
        print("mail has sent")

    Program Execution


    sending mail
    mail has sent

    To send the email, we are using the Python Standard smtplib and email modules. Both modules come prepacked with Python, and thus, you do not need to install them separately.

    In the above example, you can see that we have specified the my_address and app_generated_password variables in the open string format that is not a good Python practice.

    You definitely do not want other developers to read your password and email, so we prefer to use environmental variables. But for making this tutorial easy to understand, we have used them with a simple string.

    Check Gmail Sent Label

    After executing the above program, if you check your Gmail Sent Label , you will see that the email you sent using Python is available here.

    As you can see that your message has been saved to the Sent label, which means the message has been sent successfully. Since the receiver account is also our other account, we can check if the receiver account received the mail or not.

    On checking, we can see that we have received the mail from Hence, our task is complete.

    Send Multimedia Files With Gmail Using Python

    So far, we have learned how to use Gmail API in Python to send a mail. For that, we used the Gmail account. But if we wish to send an image as mail to someone, we have to attach the image file with the mail. Can we do that?

    Yes, we can! To attach an image file to the mail body, we can use the email module and the add_attachment method, but we also have to import the image file and read it as a binary object. For that, we will be using the Python standard imghdr module.

    #Example 2: python program to send a mail with an image attached

    import imghdr
    import smtplib
    from email.message import EmailMessage
    msg= EmailMessage()
    my_address =""   #sender address
    app_generated_password = "habebwgknjtopoxd"      #generated passcode
    msg["Subject"] ="The Email Subject"
    msg["From"]= my_address   #sender address
    msg["To"] = ""         #reciver addresss
    msg.set_content("This is the body of the email")  
    with open('photo.jpg', "rb") as file:     #open image file 
        file_data =
        file_type = imghdr.what(
        file_name =
    print("File has been attached to the message body")
    msg.add_attachment(file_data, maintype="image", 
                       subtype=file_type, filename= file_name)   #attach image file to msg
    with smtplib.SMTP_SSL("", 465) as smtp:
        smtp.login(my_address,app_generated_password)   #login to gmail
        print("sending mail\\.....")
        smtp.send_message(msg)    #send mail
        print("mail has sent!")

    Execute the Program Output

    File has been attached to the message body
    sending mail\.....
    mail has sent!

    Check the Gmail Sent Label

    As you can see, the image file has been attached to the mail and sent to the receiver's address.


    In this Python tutorial, we learned how to use Gmail API in Python to send mail. For this purpose, we used Google App Passwords API to generate a 16-character password and send emails using Gmail with Python.

    In our first Python example, we discussed how to send simple text mail, and in the second example, we detailed how to attach an image file to the mail and send it to the receiver. Therefore, now you know how you can send emails in Gmail using Python without deactivating 2SV.

    If you like this article or have any suggestions, please let us know by commenting down below.

    People are also reading:

    Leave a Comment on this Post