Email Setup Comprehensive Guide
Generated: 2025-07-23 22:00 UTC
Status: Implementation Documentation
Region: us-east4
Verified: Configuration Complete
Overview
This document provides a complete guide to the email setup for Convert To Markdown, including Gmail API configuration, environment variables, local testing, and integration with various services.
Email Architecture
Current Configuration Status
Gmail API Setup Complete
Service Account Created:
- Email:
gmail-sender@convert-to-markdown-us-east4.iam.gserviceaccount.com
- Key Location:
deploy-gcp/keys/gmail-service-account.json
- Email:
Domain-Wide Delegation Configured:
- Client ID:
116940581280353324169
- Authorized Scope:
https://www.googleapis.com/auth/gmail.send
- Status: Configured in Google Workspace Admin Console
- Client ID:
Gmail API Enabled:
- Project:
convert-to-markdown-us-east4
- API:
gmail.googleapis.com
- Project:
Environment Variables Setup
Required Environment Variables
# Primary email configuration
GMAIL_SENDER_EMAIL=lindsay@knowcode.tech # Or your authorized email
# Optional: Override service account key path
GMAIL_SERVICE_ACCOUNT_KEY=/path/to/gmail-service-account.json
Setting Environment Variables
For Local Development
Create a .env.local
file in your project root:
# .env.local
GMAIL_SENDER_EMAIL=lindsay@knowcode.tech
PROJECT_ID=convert-to-markdown-us-east4
For Cloud Functions Deployment
# When deploying functions
gcloud functions deploy free-tier-signup \
--set-env-vars="GMAIL_SENDER_EMAIL=lindsay@knowcode.tech" \
--set-env-vars="PROJECT_ID=convert-to-markdown-us-east4"
Local Testing Setup
1. Create Test Script
Create test-email-local.js
:
// test-email-local.js
require('dotenv').config({ path: '.env.local' });
const path = require('path');
// Mock the service account key path for local testing
process.env.GMAIL_SERVICE_ACCOUNT_KEY = path.join(__dirname, 'deploy-gcp/keys/gmail-service-account.json');
async function testEmailSending() {
try {
// Test configuration
console.log('š§ Configuration:');
console.log('- Sender Email:', process.env.GMAIL_SENDER_EMAIL || 'NOT SET');
console.log('- Service Account Key:', process.env.GMAIL_SERVICE_ACCOUNT_KEY || 'Using default path');
console.log('- Project ID:', process.env.PROJECT_ID || 'NOT SET');
// Import email functions
const { sendWelcomeEmailFree, sendEmail } = require('./functions/lib/email-gmail-api');
// Test email address
const testEmail = 'your-test-email@example.com'; // Change this to your email
const testApiKey = 'ctm_live_test_1234567890abcdef1234567890abcdef';
console.log('\nš§ Sending test email to:', testEmail);
// Option 1: Test welcome email
await sendWelcomeEmailFree(testEmail, testApiKey);
console.log('ā
Welcome email sent successfully!');
// Option 2: Test generic email
// await sendEmail({
// to: testEmail,
// subject: 'Test Email from Convert To Markdown',
// text: 'This is a test email.',
// html: '<p>This is a <strong>test email</strong>.</p>'
// });
} catch (error) {
console.error('ā Error sending email:', error);
if (error.code === 403) {
console.error('\nā ļø Permission denied. Check:');
console.error('1. Domain-wide delegation is set up correctly');
console.error('2. GMAIL_SENDER_EMAIL is authorized in Google Workspace');
console.error('3. Service account has correct permissions');
}
}
}
// Check dependencies
try {
require.resolve('googleapis');
require.resolve('dotenv');
testEmailSending();
} catch (e) {
console.log('š¦ Installing required packages...');
const { execSync } = require('child_process');
execSync('npm install googleapis dotenv', { stdio: 'inherit' });
console.log('\nā
Packages installed. Please run this script again.');
}
2. Install Dependencies
npm install dotenv googleapis
3. Run Local Test
# Make sure you're in the project root
cd /Users/lindsaysmith/Documents/lambda1.nosync/xlsx-docx-ppt-convert-to-md
# Run the test
node test-email-local.js
Integration Points
1. Free Tier Signup Function
File: functions/free-tier-signup/index.js
const { sendWelcomeEmailFree } = require('../lib/email-gmail-api');
// In the signup handler:
await sendWelcomeEmailFree(email, apiKey);
2. Stripe Webhook (Pro Tier)
File: functions/stripe-webhook/index.js
const { sendWelcomeEmailPro } = require('../lib/email-gmail-api');
// In the checkout.session.completed handler:
await sendWelcomeEmailPro(customer_email, apiKey);
3. Email Library Implementation
File: functions/lib/email-gmail-api.js
Key components:
- Uses Google Auth with service account
- Implements domain-wide delegation via
subject
parameter - Creates RFC 2822 formatted emails
- Handles both text and HTML content
Troubleshooting
Common Issues and Solutions
1. Permission Denied (403 Error)
Cause: Domain-wide delegation not properly configured
Solution:
- Verify Client ID
116940581280353324169
in Google Admin Console - Ensure scope
https://www.googleapis.com/auth/gmail.send
is authorized - Check GMAIL_SENDER_EMAIL is correct
2. Service Account Key Not Found
Cause: Incorrect path to service account key
Solution:
// Set explicit path
process.env.GMAIL_SERVICE_ACCOUNT_KEY = '/absolute/path/to/key.json';
3. Invalid Email Sender
Cause: Using email not authorized in domain-wide delegation
Solution: Use an email address from your Google Workspace domain
4. Authentication Scope Error
Cause: Missing or incorrect scopes
Solution: Ensure scope includes https://www.googleapis.com/auth/gmail.send
Production Deployment
Function Deployment with Email Config
# Deploy free tier signup
gcloud functions deploy free-tier-signup \
--gen2 \
--runtime=nodejs20 \
--region=us-east4 \
--source=functions/free-tier-signup \
--entry-point=freeTierSignup \
--trigger-http \
--allow-unauthenticated \
--set-env-vars="GMAIL_SENDER_EMAIL=noreply@convert-to-markdown.com,PROJECT_ID=convert-to-markdown-us-east4" \
--memory=256MB \
--timeout=30s
# Deploy Stripe webhook
gcloud functions deploy stripe-webhook \
--gen2 \
--runtime=nodejs20 \
--region=us-east4 \
--source=functions/stripe-webhook \
--entry-point=stripeWebhook \
--trigger-http \
--allow-unauthenticated \
--set-env-vars="GMAIL_SENDER_EMAIL=noreply@convert-to-markdown.com,STRIPE_SECRET_KEY=sk_live_xxx,STRIPE_WEBHOOK_SECRET=whsec_xxx" \
--memory=512MB \
--timeout=60s
Email Templates
Free Tier Welcome Email
- Subject: "Welcome to Convert To Markdown - Your API Key Inside! "
- Contains: API key, usage limits, quick start guide
- CTA: Link to API documentation
Pro Tier Welcome Email
- Subject: "Welcome to Convert To Markdown Pro! "
- Contains: API key, pro benefits, dashboard link
- CTA: Links to dashboard and API docs
Security Considerations
- API Keys: Never log raw API keys, only send via email
- Service Account Key: Keep secure, never commit to git
- Email Validation: Validate email format before sending
- Rate Limiting: Implement on signup endpoints to prevent abuse
Monitoring
What to Monitor
- Email send success rate
- Failed email attempts
- API quota usage
- Service account authentication errors
Logging
The email library logs:
- Successful sends:
Email sent successfully to [email]
- Errors with context for debugging
- No sensitive data (API keys) logged
Testing Checklist
- Local test script runs without errors
- Test email received with correct content
- API key displays correctly in email
- HTML renders properly in email client
- Text version is readable
- Links in email work correctly
- Subject line appears correctly
- From address shows authorized sender
Quick Reference
File Locations
- Service Account Key:
deploy-gcp/keys/gmail-service-account.json
- Email Library:
functions/lib/email-gmail-api.js
- Test Script:
test-email-local.js
- Environment Config:
.env.local
Key Values
- Service Account:
gmail-sender@convert-to-markdown-us-east4.iam.gserviceaccount.com
- Client ID:
116940581280353324169
- API Scope:
https://www.googleapis.com/auth/gmail.send
Next Steps:
- Create
.env.local
with your email settings - Update test email address in
test-email-local.js
- Run local test to verify setup
- Deploy functions with environment variables