A production-ready, lightweight email notification service for the MyMindSpace mental wellness platform. Send beautiful, branded email notifications with a simple REST API.
- π Simple REST API - Single endpoint for sending emails
- π§ Multiple Providers - Gmail, SMTP, or test accounts
- π¨ Beautiful Templates - Professional HTML emails with MyMindSpace branding
- π‘οΈ Security First - Rate limiting, input validation, CORS protection
- π³ Docker Ready - Production-ready containerization
- π Health Monitoring - Built-in health checks and status endpoints
- π§ͺ Fully Tested - Comprehensive test suite with Jest
- Node.js 18+
- Gmail account with App Password (recommended)
cd Email
npm install
copy .env.example .env
# Edit .env with your email credentials
- Enable 2-Factor Authentication on Gmail
- Generate App Password: Google Account Settings β Security β App Passwords
- Update your
.env
file:EMAIL_SERVICE=gmail EMAIL_USER=your-email@gmail.com EMAIL_APP_PASSWORD=your-16-character-app-password EMAIL_FROM=MyMindSpace <your-email@gmail.com>
npm start # Production
npm run dev # Development with auto-reload
npm test # Run tests
POST /api/email/send
Send a personalized email notification to any recipient.
Request Body:
{
"email": "user@example.com", // Required: Valid email address
"name": "John Doe", // Required: Recipient name (1-100 chars)
"content": "Your message here...", // Required: Email content (1-5000 chars)
"subject": "Custom Subject", // Optional: Email subject (max 200 chars)
"priority": "normal" // Optional: low, normal, high
}
Success Response (200):
{
"success": true,
"message": "Email sent successfully",
"messageId": "unique-message-id",
"timestamp": "2025-08-28T10:30:00.000Z"
}
Error Response (400/500):
{
"success": false,
"error": "Validation Error",
"details": "Please provide a valid email address"
}
GET /api/email/status
Get current service status and configuration.
Response:
{
"success": true,
"service": "Email Notification Service",
"status": "Active",
"provider": "gmail",
"timestamp": "2025-08-28T10:30:00.000Z"
}
GET /health
Basic health check for monitoring and load balancers.
Response:
{
"status": "OK",
"service": "MyMindSpace Email Service",
"timestamp": "2025-08-28T10:30:00.000Z"
}
Variable | Required | Default | Description |
---|---|---|---|
PORT |
No | 3003 |
Server port |
NODE_ENV |
No | development |
Environment mode |
EMAIL_SERVICE |
No | gmail |
Email provider (gmail/smtp/test) |
EMAIL_USER |
Yes | - | Gmail username or SMTP user |
EMAIL_APP_PASSWORD |
Yes | - | Gmail App Password or SMTP password |
EMAIL_FROM |
No | EMAIL_USER |
From address with name |
RATE_LIMIT_WINDOW |
No | 15 |
Rate limit window (minutes) |
RATE_LIMIT_MAX |
No | 100 |
Max requests per window |
- Enable 2-Factor Authentication in your Google Account
- Generate App Password:
- Go to Google Account Security
- Select "App passwords"
- Choose "Mail" and generate password
- Configure Environment:
EMAIL_SERVICE=gmail EMAIL_USER=your-email@gmail.com EMAIL_APP_PASSWORD=your-16-character-password EMAIL_FROM=MyMindSpace <your-email@gmail.com>
For other email providers or custom SMTP servers:
EMAIL_SERVICE=smtp
SMTP_HOST=smtp.your-provider.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-username
SMTP_PASSWORD=your-password
For development without real email sending:
EMAIL_SERVICE=test
This uses Ethereal test accounts and provides preview URLs in console logs.
Basic Notification:
curl -X POST http://localhost:3003/api/email/send ^
-H "Content-Type: application/json" ^
-d "{\"email\":\"user@example.com\",\"name\":\"John Doe\",\"content\":\"Welcome to MyMindSpace! Your wellness journey starts here.\"}"
High Priority Alert:
curl -X POST http://localhost:3003/api/email/send ^
-H "Content-Type: application/json" ^
-d "{\"email\":\"user@example.com\",\"name\":\"Jane Smith\",\"content\":\"Crisis support resources are available 24/7.\",\"subject\":\"Urgent: Support Available\",\"priority\":\"high\"}"
const axios = require('axios');
// Simple notification function
async function sendNotification(email, name, content, options = {}) {
try {
const response = await axios.post('http://localhost:3003/api/email/send', {
email,
name,
content,
subject: options.subject || 'MyMindSpace Notification',
priority: options.priority || 'normal'
});
console.log('Email sent:', response.data.messageId);
return response.data;
} catch (error) {
console.error('Email failed:', error.response?.data || error.message);
throw error;
}
}
// Usage examples
await sendNotification('user@example.com', 'John', 'Welcome to MyMindSpace!');
await sendNotification('user@example.com', 'Jane', 'Your analysis is ready!', {
subject: 'Mood Analysis Complete',
priority: 'normal'
});
Invoke-RestMethod -Uri "http://localhost:3003/api/email/send" `
-Method POST `
-ContentType "application/json" `
-Body '{"email":"user@example.com","name":"Test User","content":"PowerShell test notification!"}'
# Build and run with Docker
docker build -t mymindspace-email .
docker run -d --name email-service -p 3003:3003 --env-file .env mymindspace-email
# Or use Docker Compose
docker-compose up -d
# Deploy directly to Cloud Run
gcloud run deploy email-service --source . --platform managed --region us-central1 --allow-unauthenticated
# Set environment variables
gcloud run services update email-service \
--set-env-vars EMAIL_USER=your-email@gmail.com,EMAIL_APP_PASSWORD=your-app-password \
--region us-central1
Create a .env
file for Docker deployment:
NODE_ENV=production
EMAIL_SERVICE=gmail
EMAIL_USER=your-email@gmail.com
EMAIL_APP_PASSWORD=your-app-password
EMAIL_FROM=MyMindSpace <your-email@gmail.com>
π See DOCKER_DEPLOYMENT.md for complete deployment guide.
- β Rate Limiting - 100 requests per 15 minutes per IP
- β Input Validation - Joi schema validation for all inputs
- β CORS Protection - Configurable cross-origin requests
- β Environment Security - Sensitive data in environment variables
- β Error Handling - Comprehensive error responses without data leaks
- β Docker Security - Non-root user, Alpine Linux base
- β Connection Pooling - Reusable SMTP connections
- β Async Operations - Non-blocking email sending
- β Health Monitoring - Automatic service recovery
- β Resource Limits - Memory and CPU constraints in Docker
- β Lightweight Base - Alpine Linux for minimal footprint
The service automatically generates beautiful emails with:
- Responsive HTML Design - Works on all devices
- MyMindSpace Branding - Professional visual identity
- Plain Text Fallback - Compatible with all email clients
- Personalized Content - Dynamic name and content insertion
- Clean, modern design with gradient header
- Professional typography and spacing
- Mobile-responsive layout
- Branded footer with wellness messaging
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run with coverage report
# Test service health
curl http://localhost:3003/health
# Test email sending
curl -X POST http://localhost:3003/api/email/send \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","name":"Test User","content":"Test message"}'
# Test service status
curl http://localhost:3003/api/email/status
# Development logs
npm run dev
# Docker logs
docker logs -f mymindspace-email
# Cloud Run logs
gcloud logging read "resource.type=cloud_run_revision"
- Health Endpoint:
GET /health
- Basic service health - Status Endpoint:
GET /api/email/status
- Detailed service status - Docker Health Checks - Automatic container monitoring
- Cloud Run Health Checks - Built-in uptime monitoring
All errors are logged with:
- Timestamp and severity level
- Request context and user information
- Detailed error messages for debugging
- Email sending status and message IDs
Status Code | Error Type | Description |
---|---|---|
400 |
Validation Error | Invalid input data (email format, missing fields) |
429 |
Rate Limit | Too many requests from same IP |
500 |
Email Send Failed | SMTP connection or authentication issues |
500 |
Internal Server Error | Unexpected server errors |
π΄ "Gmail Authentication Failed"
- Verify 2FA is enabled on Gmail account
- Regenerate Gmail App Password
- Check EMAIL_USER and EMAIL_APP_PASSWORD in .env
π΄ "Rate Limit Exceeded"
- Wait 15 minutes or adjust rate limits in server.js
- Consider using multiple email accounts for high volume
π΄ "Container Health Check Failed"
- Check if service is running on correct port
- Verify environment variables are set correctly
- Review Docker logs for startup errors
This service integrates seamlessly with the main MyMindSpace platform for:
- Welcome emails for new user registrations
- Daily mood reminders and wellness check-ins
- Achievement notifications for skill progression
- Analysis ready alerts for mood/journal insights
- Crisis support resource notifications
- Appointment reminders for therapy sessions
- Resource recommendations based on user needs
- Community updates and group activities
- Feature announcements and platform updates
- Maintenance notifications and service updates
- Feedback requests and user surveys
- Newsletter content and wellness tips
Internet β Load Balancer β Google Cloud Run β Email Service
β
Gmail SMTP / Custom SMTP
- Horizontal Scaling: Cloud Run auto-scales based on traffic
- Rate Limiting: Adjust limits based on email provider quotas
- Multiple Providers: Consider backup SMTP providers for reliability
- Monitoring: Set up alerts for service health and email delivery rates
Development:
NODE_ENV=development
EMAIL_SERVICE=test # Uses Ethereal for safe testing
Staging:
NODE_ENV=staging
EMAIL_SERVICE=gmail
EMAIL_USER=staging@yourdomain.com
Production:
NODE_ENV=production
EMAIL_SERVICE=gmail
EMAIL_USER=notifications@yourdomain.com
RATE_LIMIT_MAX=1000 # Higher limits for production
Your MyMindSpace Email Notification Service is production-ready with:
- β Secure authentication and input validation
- β Beautiful email templates with professional branding
- β Docker containerization for easy deployment
- β Comprehensive monitoring and health checks
- β Complete documentation and examples
- β Test suite for reliability assurance
Start sending wellness notifications today! π§β¨
- Documentation: DOCKER_DEPLOYMENT.md
- Issues: Create issues in the project repository
- Email: Technical questions and support requests