Mail Service
Relevant source files
The following files were used as context for generating this wiki page:The Mail Service is a core component of the Traduora API, responsible for sending all transactional emails to users. Implemented as a NestJS injectable service, it leverages the nodemailer library to handle email transport and handlebars for dynamic email templating. Its primary functions include sending welcome emails, password reset instructions, and project invitations.
The service is designed to be configurable via environment variables, allowing it to adapt to different deployment environments. It also includes a debug mode that previews emails in a web browser instead of sending them, which is useful for development and testing.
Architecture and Initialization
The MailService is initialized within the NestJS dependency injection framework. Its constructor is responsible for setting up the email transporter and pre-compiling email templates.
Sources: api/src/services/mail.service.ts:13-50
Configuration
The service's behavior is controlled by configuration values, primarily for the SMTP transport. These settings are sourced from api/src/config.ts which reads environment variables.
| Environment Variable | Description | Default Value |
|---|---|---|
TR_MAIL_HOST | SMTP server host. | undefined |
TR_MAIL_PORT | SMTP server port. | 587 |
TR_MAIL_SECURE | Whether to use a secure connection (TLS). | false |
TR_MAIL_USER | Username for SMTP authentication. | undefined |
TR_MAIL_PASS | Password for SMTP authentication. | undefined |
TR_MAIL_SENDER | The "From" address for outgoing emails. | traduora@localhost |
TR_MAIL_REJECT_SELFSIGNED | Whether to reject self-signed SSL certificates. | false |
TR_MAIL_DEBUG | If true, previews emails in a browser instead of sending. | false |
Sources: api/src/config.ts:101-118, api/src/services/mail.service.ts:31-41
Transporter Setup
In the constructor, an SMTP transporter is created using nodemailer.createTransport(). If the TR_MAIL_HOST is not provided, the transporter is not created, and a warning is logged to the console, unless the environment is e2e. This prevents the application from crashing if email is not configured.
// File: api/src/services/mail.service.ts:30-49
constructor() {
const options = {
host: config.mail.host,
port: config.mail.port,
secure: config.mail.secure,
auth: {
user: config.mail.auth.user,
pass: config.mail.auth.pass,
},
tls: {
// do not fail on invalid certs
rejectUnauthorized: config.mail.rejectSelfSigned,
},
};
this.transporter = options.host ? createTransport(options) : undefined;
if (!this.transporter && !(config.env === 'e2e')) {
console.log(
'No email transport configured. ' +
'Please check the documentation on how to configure ' +
'the mail service at: https://docs.traduora.co/docs/configuration',
);
}
this.from = config.mail.sender;
}
The following diagram illustrates the initialization logic of the MailService.
Email Templating
The service uses Handlebars for rendering email content from template files. Templates are located in the directory specified by config.templatesDir (within a mail subdirectory).
Template Compilation
During initialization, the service pre-compiles a set of known templates using the mustCompileTemplate method. This method reads a file, converts it to a UTF-8 string, and compiles it into a Handlebars template function.
// File: api/src/services/mail.service.ts:121-124
private mustCompileTemplate(name: string): Handlebars.TemplateDelegate<any> {
const contents = readFileSync(join(config.templatesDir, 'mail', name)).toString('utf-8');
return Handlebars.compile(contents);
}
The compiled templates are stored in the knownTemplates property for reuse.
| Template Name | File Name | Purpose |
|---|---|---|
welcome | welcome.txt | Sent to new users upon registration. |
passwordChanged | password-changed.txt | Notifies a user that their password has been changed. |
passwordResetToken | password-reset-token.txt | Provides a user with a token to reset their password. |
invitedToProject | invited-to-project.txt | Informs an existing user they've been added to a project. |
invitedToPlatform | invited-to-platform.txt | Invites a new user to the platform and a specific project. |
Sources: api/src/services/mail.service.ts:20-26
Template Example
Templates are simple text files that use Handlebars syntax for variable substitution.
// File: api/src/templates/mail/password-reset-token.txt
Hi {{user.name}},
You have requested to reset your password. Please use the following token to proceed:
{{resetToken}}
You can reset your password at: {{endpoint}}
If you did not request a password reset, please ignore this email.
This template uses variables like user.name, resetToken, and endpoint which are passed in when the email is generated.
Sources: api/src/templates/mail/password-reset-token.txt
Sending Emails
The private send method is the core of the service's sending logic. It takes a SendMailOptions object from nodemailer and dispatches the email.
// File: api/src/services/mail.service.ts:112-119
private async send(message: SendMailOptions): Promise<any> {
if (this.transporter) {
await this.transporter.sendMail(message);
}
if (config.mail.debug) {
// createTransport({jsonTransport: true})
await previewEmail(message);
}
}
If the transporter is configured, transporter.sendMail is called. If config.mail.debug is true, preview-email is used to open the composed email in the default web browser, which is useful for local development without a configured SMTP server.
Sources: api/src/services/mail.service.ts:112-119
Public API and Use Cases
The MailService exposes several public methods, each corresponding to a specific transactional email event. These methods are called by other services, such as the AuthController.
| Method | Description | Template Used |
|---|---|---|
welcomeNewUser(user: User) | Sends a welcome email to a newly registered user. | welcome |
passwordChanged(user: User) | Confirms a successful password change. | passwordChanged |
passwordResetToken(user: User, token: string) | Sends a password reset token and link. | passwordResetToken |
invitedToProject(user: ProjectUser) | Notifies a user they have been added to a project. | invitedToProject |
invitedToPlatform(invite: Invite) | Sends an invitation to a new user to join a project. | invitedToPlatform |
Sources: api/src/services/mail.service.ts:52-110
Example Flow: Password Reset
The password reset flow demonstrates how AuthController interacts with UserService and MailService.
- A user submits their email to the
/api/v1/auth/forgot-passwordendpoint. AuthControllercallsuserService.forgotPassword().UserServicegenerates a reset token and saves it.AuthControllerthen callsmailService.passwordResetToken()with the user object and the token.MailServicerenders thepassword-reset-token.txttemplate and sends the email.
This sequence diagram shows the interactions for a password reset request.