pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
import base64
import os
import json
# Step 1: Define constants
SCOPES = ['<https://www.googleapis.com/auth/gmail.send>']
CLIENT_ID = "1088850741773-2v0hh8m6a4j3f0164tu3v2ui9ubsimbm.apps.googleusercontent.com"
CLIENT_SECRET = [ADD SECRET HERE]
# Step 2: Authenticate
def authenticate():
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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('credentials.json', SCOPES)
# Try different ports if 8080 is blocked
for port in range(8080, 8090):
try:
creds = flow.run_local_server(port=port)
break
except OSError:
continue
# Save the credentials for future use
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
# Step 4: Send Email
def send_email(service, sender, recipient, subject, body):
message = {
'raw': base64.urlsafe_b64encode(
f'From: {sender}\\r\\n'
f'To: {recipient}\\r\\n'
f'Subject: {subject}\\r\\n\\n'
f'{body}'.encode('utf-8')
).decode('utf-8')
}
try:
sent_message = service.users().messages().send(userId="me", body=message).execute()
print(f"Message sent successfully: {sent_message}")
return sent_message
except Exception as e:
print(f"An error occurred: {e}")
raise e
# Main function
if __name__ == "__main__":
# Authenticate
creds = authenticate()
service = build('gmail', 'v1', credentials=creds)
# Send email
send_email(
service,
"[email protected]",
"[email protected]",
"Test Email Subject",
"This is the body of the email."
)
{"token": "ya29.a0AeDClZAg9QCyAvZRSbRjcHCVeMfyE4bIe8yfZpWpFuOU_fbR2koHOXNTsh1l15L734H0MMuAAtRBZKrH9ivQGyPY91Gpndj-6HvDHiaNVyxa8kbipcOAQdtDieElGltKHAxmTlDjzoPK3Xcwud5dwkLYR-Kcf7ZGUpZc8OuCaCgYKAW8SAQ4SFQHGX2MiX0VgXj8hma0Y9aZAMTmmgQ0175", "refresh_token": "1//01eUHI41jTxjOCgYIARAAGAESNwF-L9IriiN2k33N9ulEGPrcCgaRt5JbfqgpyHh7WbG54MPrqvzyz10C52wCH8sFUhqaXNG2-M0", "token_uri": "<https://oauth2.googleapis.com/token>", "client_id": "1088850741773-2v0hh8m6a4j3f0164tu3v2ui9ubsimbm.apps.googleusercontent.com", "client_secret": "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", "scopes": ["<https://www.googleapis.com/auth/gmail.send>"], "universe_domain": "googleapis.com", "account": "", "expiry": "2024-11-23T04:38:16.729903Z"}
{"installed":{
"client_id":"1088850741773-2v0hh8m6a4j3f0164tu3v2ui9ubsimbm.apps.googleusercontent.com",
"project_id":"gmail-api-sender-442603",
"auth_uri":"<https://accounts.google.com/o/oauth2/auth>",
"token_uri":"<https://oauth2.googleapis.com/token>",
"auth_provider_x509_cert_url":"<https://www.googleapis.com/oauth2/v1/certs>",
"client_secret":"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"}}
https://developers.google.com/gmail/api/guides?utm_source=chatgpt.com