Skip to content

Instantly share code, notes, and snippets.

@Naphier
Created March 7, 2023 23:21
Show Gist options
  • Save Naphier/1d4a29ed6194a7b02be56a1e1684b00a to your computer and use it in GitHub Desktop.
Save Naphier/1d4a29ed6194a7b02be56a1e1684b00a to your computer and use it in GitHub Desktop.
Wrote this with the ChatGPT prompt "Write Python code to send email using GMail API and a Service Account". Looks accurate though I've not tested.
import os
import base64
import google.auth
from google.oauth2 import service_account
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
from email.mime.audio import MIMEAudio
# Define the email parameters
sender = '[email protected]'
to = '[email protected]'
subject = 'Test email'
body = 'This is a test email from GMail API'
attachments = ['file1.png', 'file2.mp3']
# Create the credentials object using the Service Account key file
credentials = service_account.Credentials.from_service_account_file(
'path/to/service-account-key.json',
scopes=['https://www.googleapis.com/auth/gmail.compose'])
# Build the GMail API client
gmail_service = build('gmail', 'v1', credentials=credentials)
# Create the message object
message = MIMEMultipart()
message['to'] = to
message['subject'] = subject
# Add the body of the email
text = MIMEText(body, 'html')
message.attach(text)
# Add the attachments
for attachment in attachments:
with open(attachment, 'rb') as file:
file_data = file.read()
if attachment.endswith('.png'):
attachment_type = 'png'
elif attachment.endswith('.mp3'):
attachment_type = 'audio/mpeg'
else:
attachment_type = 'application/octet-stream'
attachment_name = os.path.basename(attachment)
attachment = MIMEAudio(file_data, _subtype=attachment_type)
attachment.add_header('Content-Disposition', 'attachment', filename=attachment_name)
message.attach(attachment)
# Encode the message in base64 format
raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
# Send the email
try:
message = gmail_service.users().messages().send(userId=sender, body={'raw': raw_message}).execute()
print(F'Sent message to {to} Message Id: {message["id"]}')
except HttpError as error:
print(F'An error occurred: {error}')
message = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment