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
Asked
Active
Viewed 989 times
0

Linda Lawton - DaImTo
- 106,405
- 32
- 180
- 449

haysquare
- 45
- 1
- 5
-
try this [delegation#python](https://developers.google.com/admin-sdk/directory/v1/guides/delegation#python) swap out admin sdk for the gmail api and then use that to send your emails. – Linda Lawton - DaImTo May 26 '22 at 18:27
1 Answers
1
from google.oauth2 import service_account
from googleapiclient.discovery import build
SERVICE_ACCOUNT_FILE= 'path_to_your_json_credential_file'
DELEGATE='youremail@yourcompany.com' # 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'] = 'receiver@email.com'
message['From'] = 'your@email.com'
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

Jerbs
- 131
- 1
- 8
-
-
I have edited my previous response, check it out. I also changed the SCOPES. – Jerbs Jul 14 '22 at 14:10