UNPKG

@bhavinkumarvegad/playwright-email-utils

Version:

Reusable utilities for handling emails in Playwright tests from Yopmail, Gmail and other providers.

307 lines (260 loc) 7.46 kB
# 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 ```bash npm install @bhavinkumarvegad/playwright-email-utils ``` ## Gmail Setup ### 1. Set up Gmail API Credentials 1. Go to the [Google Cloud Console](https://console.cloud.google.com/) 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: ```env GMAIL_CLIENT_ID=your-client-id GMAIL_CLIENT_SECRET=your-client-secret ``` 2. Configure environment variables: ```bash npm install dotenv ``` Update your `playwright.config.ts`: ```typescript import 'dotenv/config'; export default defineConfig({ // ... rest of your config }); ``` 3. Generate your refresh token: ```bash npx get-gmail-token ``` 4. 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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: ```typescript { 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: ```typescript { 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: ```typescript { field: 'completeEmail', type: 'full-text' } ``` Gmail Extraction Rule Structure: ```typescript 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: ```typescript { selector: { type: 'text', value: 'Order ID:' }, action: 'textContent', description: 'Order Number' } ``` 2. **Attribute Values** (`action: 'getAttribute'`) - Extracts specific attributes (e.g., href, value) - Example: ```typescript { 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: ```typescript { selector: { type: 'role', value: { role: 'button', name: 'View Details' }}, action: 'click', description: 'Open Details' } ``` Yopmail Extraction Rule Structure: ```typescript 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