haysquare
haysquare

Reputation: 73

How can I send email using python with google workspace

I just signed up for the Google workspace business starter because of lots of recommendations from people, I would like to know how possible is it to send email via my backend API using Django, I've searched for it online but nothing comprehensive or direct, try to contact their support but not available. Thanks in advance

Upvotes: 0

Views: 2377

Answers (2)

Alexey Chernov
Alexey Chernov

Reputation: 69

I asked a question at https://support.google.com/a/thread/299620559 . The complete process then was:

  1. Set up the SMTP relay: https://support.google.com/a/answer/176600?hl=en, "option 1"

  2. Set up the 2-factor authorization: https://support.google.com/a/answer/9176657

  3. Turn on 2FA for the user that you'll use to send emails

  4. Create the "app password" for that user: https://support.google.com/accounts/answer/185833

And after that, the simple django.core.mail.send_mail function worked!

Upvotes: 0

Jerbs
Jerbs

Reputation: 203

from google.oauth2 import service_account
from googleapiclient.discovery import build

SERVICE_ACCOUNT_FILE= 'path_to_your_json_credential_file'
DELEGATE='[email protected]'  # The service account will impersonate this user. The service account must have proper admin privileges in G Workspace.
SCOPES = ['https://mail.google.com/'] # ... or whatever scope(s) you need for your purpose
    




def connect_to_gmail():
    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    credentials_delegated = credentials.with_subject(DELEGATE)
    gmail = build('gmail', 'v1', credentials=credentials_delegated)

    # do whatever you need with it, check the exemple below :
    # new_msg_history_lst = gmail.users().history().list(userId='me',maxResults=3, startHistoryId='1', labelId='INBOX').execute()
    # print(new_msg_history_lst)

    return gmail



 def gmail_send_message(gmail): # not sure it works properly but it's a start for you
        import base64
        from email.message import EmailMessage
        from googleapiclient.errors import HttpError
    
        try:
            message = EmailMessage()
            message.set_content('This is automated draft mail')
            message['To'] = '[email protected]'
            message['From'] = '[email protected]'
            message['Subject'] = 'Automated draft'
    
            # encoded message
            encoded_message = base64.urlsafe_b64encode(message.as_bytes()) \
                .decode()
    
            create_message = {
                'raw': encoded_message
            }
            
            send_message = gmail.users().messages().send(userId='me', body=create_message).execute()
            # print(F'Message Id: {send_message["id"]}')
        except HttpError as error:
            print(F'An error occurred: {error}')
            send_message = None
        return send_message

For the above code to work it presupposes that :

  • the account is a google workspace account
  • you have created a service account, created keys for it, and downloaded them as a json
  • you have added the Domain Wide delegation for the service account, and added to it at least the same scopes as in the ones above
  • you have enabled the Gmail API

Upvotes: 2

Related Questions