How to send email using vanilla python

John Ali
3 min readMay 4, 2023

--

Python is a high-level programming language that is popular among developers for its readability, flexibility, and ease of use. One of the many things that can be done with Python is sending emails, and this can be achieved using various libraries.

In this article, we will focus on sending emails using the Gmail API. The Gmail API provides a secure and reliable way to send emails using your Gmail account.

The Gmail API allows you to programmatically access and manage Gmail mailboxes, labels, and messages. Using the Gmail API, you can send and receive emails, search for messages, and perform other operations. In this article, we’ll explore how to send an email using the Gmail API in Python.

Setting Up the Gmail API

Before we can use the Gmail API, we need to set up a project in the Google Cloud Console and obtain API credentials. Here’s how to do it:

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Navigate to the “APIs & Services” section and select “Library.”
  4. Search for “Gmail API” and enable it.
  5. Create credentials for your project by selecting “Create credentials” and choosing “OAuth client ID.”
  6. Choose “Desktop app” as the application type and enter a name for the client ID.
  7. Download the client ID credentials as a JSON file and save it in a secure location.

Installing the Google API Client Library

To interact with the Gmail API, we need to install the Google API Client Library for Python. We can do this using pip, the Python package manager:

pip install --upgrade google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

Sending an Email Using the Gmail API

Now that we have set up the Gmail API and installed the client library, let’s write some code to send an email. Here’s an example:

import os
import base64
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
def send_gmail_api():
# Load API credentials from JSON file
creds = Credentials.from_authorized_user_file("credentials.json", ["https://www.googleapis.com/auth/gmail.send"])
# Build the Gmail API service
service = build("gmail", "v1", credentials=creds)
# Create a multipart message
message = MIMEMultipart()
message["to"] = "recipient_email_address"
message["subject"] = "Gmail API Test"
# HTML content
html_content = """
<html>
<body>
<h1>Hello, World!</h1>
<p>This is a test email sent using the Gmail API.</p>
<img src="cid:image1">
</body>
</html>
"""
# Attach HTML content
message.attach(MIMEText(html_content, "html"))
# Attach an image
with open("image.jpg", "rb") as f:
img_data = f.read()
image = MIMEImage(img_data)
image.add_header("Content-ID", "<image1>")
message.attach(image)
# Encode the message in base64
raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8")
# Send the email
try:
message = service.users().messages().send(userId="me", body={"raw": raw_message}).execute()
print(f"Message Id: {message['id']}")
except HttpError as error:
print(f"An error occurred: {error}")

In the code above, we first import the necessary modules, including `googleap

If you want to LEARN MORE information on Python Join Our Public Group On LinkedIn Where We Teach Python For Free visit → LEARN PYTHON FOR FREE

Kindly Follow Me On LINKEDIN

--

--

John Ali
John Ali

Written by John Ali

Versatile Content Creator & Tech Enthusiast: DevSecOps, Machine Learning, Software Engineering, Backend & Frontend Development, Data Engineering

No responses yet