1.1.0 • Published 5 months ago

@bhavinkumarvegad/playwright-email-utils v1.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

Playwright Email Utils

A utility package to extract and interact with emails from both disposable email services (e.g., Yopmail) and Gmail using Playwright.

Features

  • Support for multiple email providers:
    • Gmail (via Gmail API)
    • Yopmail (via web interface)
  • Extract content, click links, or get attributes dynamically
  • Built-in polling for delayed email delivery
  • Advanced email content extraction with multiple strategies
  • Optional auto-delete support
  • Easy to extend for other providers

Installation

npm install @bhavinkumarvegad/playwright-email-utils

Gmail Setup

1. Set up Gmail API Credentials

  1. Go to the Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable the Gmail API for your project
  4. Create OAuth 2.0 credentials (Client ID and Client Secret)
  5. Add http://localhost to the authorized redirect URIs

2. Get Refresh Token

  1. First create a .env file in your project root with your credentials:
GMAIL_CLIENT_ID=your-client-id
GMAIL_CLIENT_SECRET=your-client-secret
  1. Configure environment variables:
npm install dotenv

Update your playwright.config.ts:

import 'dotenv/config';

export default defineConfig({
  // ... rest of your config
});
  1. Generate your refresh token:
npx get-gmail-token
  1. Follow the prompts:
    • Visit the authorization URL
    • Grant access to your Gmail account
    • Copy the code from the redirect URL
    • Paste it into the terminal
    • Add the provided configuration to your .env file

Usage Examples

Gmail Integration

Basic Email Search

import { emailUtils } from '@bhavinkumarvegad/playwright-email-utils';
import 'dotenv/config';

test('Read email from Gmail', async () => {
  const config = {
    clientId: process.env.GMAIL_CLIENT_ID!,
    clientSecret: process.env.GMAIL_CLIENT_SECRET!,
    refreshToken: process.env.GMAIL_REFRESH_TOKEN!
  };

  const email = await emailUtils.getEmail.fromGmail(config, {
    subject: 'New release on live - 1.1.0',
    from: 'sender@example.com',
    to: 'recipient@example.com',
    afterTime: '2025-06-01 00:00:00',
    beforeTime: '2025-06-01 23:59:59'
  });

  if (email) {
    console.log('Subject:', email.subject);
    console.log('From:', email.from);
    console.log('Body:', email.body);
  }
});

Advanced Content Extraction

const extractionRules = [
  {
    field: 'releaseNotes',
    type: 'between-markers',
    startMarker: 'Release Notes:',
    endMarker: 'End of Release Notes'
  },
  {
    field: 'deploymentUrl',
    type: 'regex',
    regex: /https?:\/\/[^\s<]+/
  },
  {
    field: 'fullContent',
    type: 'full-text'
  }
];

const result = await emailUtils.getEmail.fromGmailWithDetails(
  config,
  { subject: 'New Release' },
  extractionRules
);

if (result.email) {
  console.log('Release Notes:', result.extractedDetails.releaseNotes);
  console.log('URL:', result.extractedDetails.deploymentUrl);
}

Yopmail Integration

Getting a Link

const result = await emailUtils.getEmail.fromYopmail(page, 'demoInbox', 'Welcome Email', [
  {
    selector: { type: 'text', value: 'Click here' },
    action: 'getAttribute',
    attributeName: 'href',
    description: 'Reset Link'
  }
]);

Multiple Actions

const results = await emailUtils.getEmail.fromYopmail(page, 'testInbox', 'Order Confirmation', [
  // Extract text content
  {
    selector: { type: 'text', value: 'Order ID:' },
    action: 'textContent',
    description: 'Order Number'
  },
  // Click a button
  {
    selector: { type: 'role', value: { role: 'button', name: 'Track Order' }},
    action: 'click',
    description: 'Track Order Button'
  },
  // Get attribute using custom locator
  {
    selector: { type: 'locator', value: '.verification-code' },
    action: 'textContent',
    description: 'Verification Code'
  }
]);

Auto-Delete Example

const result = await emailUtils.getEmail.fromYopmail(
  page,
  'inbox123',
  'Password Reset',
  [
    {
      selector: { type: 'text', value: 'verification code is:' },
      action: 'textContent',
      description: 'Reset Code'
    }
  ],
  true // Enable auto-delete
);

Extraction Strategies

Gmail Content Extraction

When working with Gmail, you have three sophisticated extraction strategies available:

  1. Between Markers (type: 'between-markers')

    • Extracts content between specific markers in the email body
    • Ideal for structured content like release notes or verification codes
    • Example:
    {
      field: 'releaseNotes',
      type: 'between-markers',
      startMarker: 'Release Notes:',
      endMarker: 'End of Release Notes'
    }
  2. Regular Expression (type: 'regex')

    • Extracts content using regex patterns
    • Perfect for URLs, version numbers, codes, etc.
    • Example:
    {
      field: 'confirmationUrl',
      type: 'regex',
      regex: /https:\/\/confirm\.example\.com\/[a-zA-Z0-9-]+/
    }
  3. Full Text (type: 'full-text')

    • Gets the complete email body
    • Useful when you need the entire content
    • Example:
    {
      field: 'completeEmail',
      type: 'full-text'
    }

Gmail Extraction Rule Structure:

interface EmailExtractionRule {
  field: string;              // Name for the extracted content
  type: 'between-markers' | 'regex' | 'full-text';
  startMarker?: string;       // Required for 'between-markers'
  endMarker?: string;        // Required for 'between-markers'
  regex?: RegExp;            // Required for 'regex'
}

Yopmail Content Extraction

For Yopmail, you have different extraction methods based on UI interactions:

  1. Text Content (action: 'textContent')

    • Extracts text content from elements
    • Example:
    {
      selector: { type: 'text', value: 'Order ID:' },
      action: 'textContent',
      description: 'Order Number'
    }
  2. Attribute Values (action: 'getAttribute')

    • Extracts specific attributes (e.g., href, value)
    • Example:
    {
      selector: { type: 'text', value: 'Reset Password' },
      action: 'getAttribute',
      attributeName: 'href',
      description: 'Reset Link'
    }
  3. Click and Extract (action: 'click')

    • Clicks elements and can be combined with other actions
    • Example:
    {
      selector: { type: 'role', value: { role: 'button', name: 'View Details' }},
      action: 'click',
      description: 'Open Details'
    }

Yopmail Extraction Rule Structure:

interface EmailAction {
  selector: {
    type: 'text' | 'role' | 'locator';
    value: string | { role: string; name?: string };
  };
  action: 'click' | 'textContent' | 'getAttribute';
  attributeName?: string;     // Required for getAttribute
  description: string;
}

Troubleshooting

  1. Environment Variables

    • Ensure no spaces after = in .env file
    • Verify dotenv is installed and configured
    • Check environment variables are loaded
  2. Authentication Issues

    • Regenerate refresh token using npx get-gmail-token
    • Ensure all required permissions are granted
  3. Email Search Issues

    • Verify search parameters
    • Check email exists in account
    • Use retry mechanism for delayed emails

License

MIT

1.1.0

5 months ago

1.0.1

6 months ago

1.0.0

6 months ago