DevCEDTeam / CED

0 stars 0 forks source link

OAuth 2.0 Bulk Email | Vertex #138

Open DevCEDTeam opened 2 hours ago

DevCEDTeam commented 2 hours ago

The previous instructions do not include OAuth 2.0 Authorization or generating a Google Access Token for sending emails via Gmail with OAuth 2.0. Below, I will provide optimized step-by-step instructions on how to integrate OAuth 2.0 Authorization into the email-sending process, allowing you to securely send emails via Gmail without storing plain-text credentials. This ensures that emails are sent securely using Gmail's OAuth 2.0 authorization.


Objective:

Set up OAuth 2.0 Authorization for sending emails via Gmail using Google’s OAuth 2.0 API, and integrate this into the previous HTML email solution with Vertex AI Gemini.


Step 1: Create OAuth 2.0 Credentials in Google Cloud

  1. Go to the Google Cloud Console:

    • Navigate to APIs & Services > Credentials.
    • Click Create Credentials > OAuth 2.0 Client IDs.
  2. Configure OAuth Consent Screen:

    • Select the type of application (e.g., Desktop App).
    • Fill out the required fields (e.g., Application Name, etc.).
    • Make sure to add https://mail.google.com/ in the Scopes for Google APIs section for Gmail access.
    • Click Save.
  3. Download OAuth Credentials:

    • Once the OAuth client is created, download the client_secret.json file. This file contains the client ID and secret needed for authentication.

Step 2: Install Required Libraries

To handle OAuth 2.0 authorization, you will need to install the google-auth and google-auth-oauthlib Python libraries:

pip install google-auth google-auth-oauthlib google-auth-httplib2
pip install google-api-python-client google-auth-oauthlib google-auth-httplib2

Step 3: Generate Google Access Token Using OAuth 2.0

In this step, we will generate an OAuth 2.0 access token to authorize sending emails via Gmail. This token is used to authenticate the email-sending process.

3.1 Python Script to Generate Access Token

import os
import pickle
import google.auth
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# Set the scope for Gmail access
SCOPES = ['https://mail.google.com/']

def generate_gmail_token():
    creds = None

    # Token.pickle stores the user's credentials between runs
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)

    # If no valid credentials are available, generate the authorization URL
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # Run the OAuth 2.0 flow to get new credentials
            flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', SCOPES)
            creds = flow.run_local_server(port=0)

        # Save the credentials for future runs
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    return creds

# Call this function to generate the token
if __name__ == "__main__":
    creds = generate_gmail_token()
    print("Access token generated successfully.")

Explanation:


Step 4: Send Email via Gmail with OAuth 2.0 Authorization

Now that we have the access token, we can use Gmail's API to send emails securely.

4.1 Modify the Python Script for Sending Emails Using OAuth 2.0

import base64
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email_with_oauth2(to_email, email_content):
    # Step 1: Load the Gmail API credentials
    creds = Credentials.from_authorized_user_file('token.pickle', SCOPES)

    # Step 2: Build the Gmail API service
    service = build('gmail', 'v1', credentials=creds)

    from_email = "you@gmail.com"
    subject = "Your AI-enhanced Email with OAuth2"

    # Step 3: Create the HTML email body
    html_body = f"""
    <html>
    <body>
        <h3>Hello,</h3>
        <p>This email contains an AI-generated response from Vertex AI:</p>
        <blockquote>{email_content}</blockquote>
        <p>If you no longer wish to receive emails from us, <a href="https://yourserver.com/unsubscribe?email={to_email}">click here to unsubscribe</a>.</p>
        <img src="https://yourserver.com/tracking_pixel?email={to_email}" width="1" height="1" />
    </body>
    </html>
    """

    # Step 4: Construct the email message
    msg = MIMEMultipart("alternative")
    msg["From"] = from_email
    msg["To"] = to_email
    msg["Subject"] = subject

    part = MIMEText(html_body, "html")
    msg.attach(part)

    # Encode the message
    encoded_message = base64.urlsafe_b64encode(msg.as_bytes()).decode()

    # Step 5: Send the email via Gmail API
    try:
        message = {
            'raw': encoded_message
        }
        send_message = service.users().messages().send(userId="me", body=message).execute()
        print(f"Message sent successfully: {send_message['id']}")
    except Exception as error:
        print(f"An error occurred: {error}")

# Example usage
if __name__ == "__main__":
    email_content = "This is a sample email message processed by Vertex AI."
    send_email_with_oauth2("recipient@example.com", email_content)

Explanation:

  1. OAuth 2.0 Authorization:
    • We use the credentials from token.pickle (generated in step 3) to authorize the Gmail API.
  2. Gmail API:
    • The Gmail API is used to send the email using the messages().send() method.
  3. Email Construction:
    • The email is composed as HTML with a tracking pixel and an unsubscribe link, as before.
  4. Base64 Encoding:
    • Gmail API requires the email to be encoded in Base64 format before sending.

Step 5: Deploying the OAuth 2.0 Script with Cloud Functions

Deploy the OAuth-enabled email script using Google Cloud Functions.

5.1 Update main.tf to Deploy the OAuth 2.0 Enabled Cloud Function

resource "google_cloudfunctions_function" "vertex_oauth_email_function" {
  name        = "vertexOAuthEmailFunction"
  runtime     = "python39"
  available_memory_mb = 512
  entry_point = "send_email_with_oauth2"
  source_archive_bucket = google_storage_bucket.email_function_bucket.name
  source_archive_object = "email_function_vertex_oauth.zip"
  trigger_http = true

  environment_variables = {
    GCP_PROJECT_ID = var.project_id
  }
}

5.2 Package Python Code and Deploy the Cloud Function

zip -r email_function_vertex_oauth.zip process_email_oauth.py requirements.txt token.pickle

Step 6: Testing OAuth 2.0 Integration

  1. Generate Token:

    • Run the script to generate the OAuth 2.0 token by calling the generate_gmail_token() function.
  2. Send Test Emails:

    • Send test emails using the send_email_with_oauth2() function.
    • Verify that the emails are delivered using OAuth 2.0 Authorization.
  3. Monitor Logs:

    • Check the logs in Google Cloud Console to ensure that the emails are sent successfully and the OAuth process is functioning correctly.

Conclusion

By following these steps, you have integrated OAuth 2.0 Authorization into your email management system, allowing you to securely send HTML emails via Gmail using OAuth 2.0. This solution ensures that you no longer need to store plain-text email credentials and can leverage Google’s OAuth 2.0 API to send emails securely.