top of page

How to Integrate GMail API with Django

Django is one of the popular Python Framework used to develop web applications. It follows the MVT (Model View Template) architectural pattern. It provides most of the features like Handling the backend, Server and database. You can use Normal frontend and other Frontend frameworks like ReactJs, AngularJs, etc as well with Django.


Django also provides by default SMTP feature to Send email. You can use that SMTP backend and Integrate Your SMTP email server with django and start sending emails. But, When it comes with Gmail SMTP server integration. It makes the process easier but Insecure because you have to enable less secure access.


If you want to Integrate your Google Mail in your Django project, there is also another way of integrating it. You can use Gmail API provied by Google instead of Gmail SMTP Servier. follow the below process to integrate Gmail API with your project.


How to Integrate Gmail API with Django?

1. First of all, Open Your django Project in any Codeeditor.

2. Now, Activate your Python Virtual Environment.

3. Install these below module using the command "pip install <module_name>

- google-auth-oauthlib

- google

- google-api-python-client

4. After installing above modules, Create a file named gmail.py in your project root directory.

5. Import all these modules in your Gmail.py file

import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pickle
import os
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request 

6. Define the Base directory and Email Scope like this


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://mail.google.com/']


7. Now, We will define get_service function below the Email Scope



def get_service():
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                os.path.join(BASE_DIR, 'static/client_secret.json'), SCOPES)
            creds = flow.run_local_server(port=8001)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    return service

8. Define Send message and other functions required for GMail API below the get_service function



def send_message(service, user_id, message):
    try:
        message = service.users().messages().send(userId=user_id,
                body=message).execute()

        print('Message Id: {}'.format(message['id']))

        return message
    except Exception as e:
        print('An error occurred: {}'.format(e))
        return None

def create_message_with_attachment(
    sender,
    to,
    subject,
    message_text,
    ):
    message = MIMEMultipart()
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    msg = MIMEText(message_text)
    message.attach(msg)

    raw_message = \
        base64.urlsafe_b64encode(message.as_string().encode('utf-8'))
    return {'raw': raw_message.decode('utf-8')}
 

def sendingMessage(msgto,subject,message):
    service = get_service()
    user_id = 'me'
    msg = create_message_with_attachment('<email-from>', <email-to>, <subject>,<message>)
    send_message(service, user_id, msg)

9. Now Save your File

10. Now, You have to Enable Gmail API Google Cloud Console.


11 . Visit Google Cloud link here and Enable GMail API.



12. Tap on Menu Icon>API and Services and Select Credentials



13. Click Create Credentials and select OAuth Client ID.

14. Create OAuth Client with Default options (add "http://localhost:8001/" in Url section).

15. At last, you will get Json file. So, Download it.

16. Copy the json file in your project static directory where gmail.py file is available.

17. Rename your json file to "client_secret.json"

18. Open a new terminal and Type the following command "python gmail.py"

19. It will open a link your default browser.

20. Select your google account in which you have enabled Gmail Api.

21 . It will generate token.picke file inside your project.

22. Now, Everything in perfect. You can just import the gmail file in any of your app views and start sending email.


For Example:


from gmail import sendingMessage

sendingMessage(<email-to>,<subject>,<message>)

#this function will send sms to the given email id from your Gmail account.

If you need any help related to Python and Django, CodersArts Expert Team will provide you help in your Project, Assignments, etc.




bottom of page