Email Service
The Email Service component provides a production-ready solution for sending emails in Servercn using nodemailer. It supports multiple email providers including Gmail, SMTP servers, SendGrid, and more.
Features
- Multiple email providers - Gmail, SMTP, SendGrid, AWS SES, and more
- HTML and plain text emails - Support for both HTML and text content
- Attachments - Send files as email attachments
- Multiple recipients - Support for CC, BCC, and multiple recipients
- Type-safe - Full TypeScript support
- Error handling - Comprehensive error handling and validation
- Email verification - Verify email configuration before sending
Installation Guide
Install this component using the following command:
npx servercn-cli add email-servicePrerequisites
Gmail Setup (Recommended for Development)
- Enable 2-Step Verification on your Google Account
- Generate an App Password:
- Go to Google Account → Security → 2-Step Verification → App passwords
- Create a new app password for "Mail"
- Copy the generated password
Environment Variables
Add the following to your .env file:
SMTP Server
Resend
Basic Implementation
1. NodeMailer
1. Add nodemailer configuration
MVC Path: src/configs/nodemailer.ts
Feature Path: src/shared/configs/nodemailer.ts
2. Send Email Function
MVC Path: src/utils/send-mail.ts
Feature Path: src/shared/utils/send-mail.ts
2. Resend
1. Resend configuration
MVC Path: src/configs/resend.ts
Feature Path: src/shared/configs/resend.ts
2. Send Email Function
MVC Path: src/utils/send-mail.ts
Feature Path: src/shared/utils/send-mail.ts
Usage Examples
1. Send HTML Email
2. Send Email with Resend
Best Practices
- Use environment variables - Never hardcode email credentials
- Validate email addresses - Validate recipient emails before sending
- Handle errors gracefully - Implement proper error handling and logging
- Use HTML templates - Use template engines for consistent email design
- Rate limiting - Implement rate limiting for email endpoints
- Email queuing - Use job queues (Bull, BullMQ) for bulk emails
- Test emails - Use services like Mailtrap for testing in development
Security Considerations
- App Passwords - Use app-specific passwords for Gmail
- Environment Variables - Store credentials securely
- Rate Limiting - Prevent email spam and abuse
- Input Validation - Validate email addresses and content
- HTTPS - Use secure connections (EMAIL_SECURE=true for port 465)