DevCEDTeam / CED

0 stars 0 forks source link

Description #2 #125

Open DevCEDTeam opened 1 year ago

DevCEDTeam commented 1 year ago

Python

Certainly, here's the same instructions segmented into Google Colab cells:

Google Colab Cell 1: Install Required Libraries

In this cell, you'll install the necessary Python libraries.

!pip install google-auth google-auth-oauthlib google-auth-httplib2
!pip install requests requests-oauthlib pyjwt

Google Colab Cell 2: Authenticate with Gmail using OAuth 2.0

In this cell, you'll authenticate with Gmail using OAuth 2.0.

from __future__ import print_function

import base64
from email.message import EmailMessage

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

import os  # Import the os module

def gmail_send_message():
    """Create and send an email message
    Print the returned message id
    Returns: Message object, including message id

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    # Authenticate the user and obtain user credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request

    SCOPES = ['https://www.googleapis.com/auth/gmail.send']
    creds = None

    # The file token.json stores the user's access and refresh tokens,
    # and is created automatically when the authorization flow completes for the first time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # Modify this line to provide the correct path to your "credentials.json" file
            credentials_file = '/content/drive/MyDrive/projects/programs/service_account.json'
            flow = InstalledAppFlow.from_client_secrets_file(
                credentials_file, SCOPES)  # Use the correct path here
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('gmail', 'v1', credentials=creds)
        message = EmailMessage()

        message.set_content('This is an automated draft mail')

        message['To'] = 'team@cfored.com'
        message['From'] = 'team@cfored.com'
        message['Subject'] = 'Automated draft'

        # Encoded message
        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

        create_message = {
            'raw': encoded_message
        }
        # Send the message
        send_message = service.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

if __name__ == '__main__':
    gmail_send_message()

Google Colab Cell 3: Authenticate with Mautic and Generate Token Tags

In this cell, you'll authenticate with Mautic, obtain an access token, and generate token tags.

import requests
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import jwt
from datetime import datetime, timedelta

# Mautic OAuth 2.0 credentials
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
mautic_base_url = 'https://your-mautic-instance.com'
token_url = f'{mautic_base_url}/oauth/v2/token'

# Create a client
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)

# Fetch the token
token = oauth.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)

# Get the access token
access_token = token['access_token']

Google Colab Cell 4: Assign Token Tags to Node Mailer Email Contacts and Generate Dynamic URL Links

In this cell, you'll assign token tags to Node Mailer email contacts and generate dynamic URL links.

# In your Node Mailer code, for each email contact, assign a token tag and generate a dynamic URL link.
# Use the access_token and dynamic_url in your email content.

# Create a token tag (replace with your custom tag)
token_tag = 'unique_tag_for_email'

# Calculate the expiration timestamp for the JWT token (e.g., 24 hours from now)
expiration_time = datetime.utcnow() + timedelta(hours=24)
exp_timestamp = expiration_time.timestamp()

# JWT payload for Mautic URL tracking
jwt_payload = {
    'exp': int(exp_timestamp),
    'tags': token_tag,
}

# Generate the JWT token for URL tracking
jwt_token = jwt.encode(jwt_payload, 'YOUR_SECRET_KEY', algorithm='HS256')

# Create the dynamic URL link
dynamic_url = f'{mautic_base_url}/mtracking/{jwt_token}/EMAIL_TEMPLATE_ID'

Google Colab Cell 5: Send Emails with Token Tags and Dynamic URLs

In this cell, you'll send emails with token tags and dynamic URL links.

# For each contact in Node Mailer:
to = 'recipient@example.com'  # Replace with the recipient's email address
subject = 'Test email'
body = f'This is a test email sent via the Gmail API. Click here to track: {dynamic_url}'

send_email(to, subject, body)

Make sure to run these cells sequentially, and replace placeholders with your specific details and credentials.