I’m building a feature where the frontend sends a POST request to /mailer/inform
with an array of email addresses. This triggers sending individual emails to those addresses. I’m using Server-Sent Events (SSE) at the /mailer/email-events
endpoint to provide real-time updates to the frontend about the status of each email being sent (success/failure). I expected the SSE connection to close automatically after all email statuses were sent.
Here’s my current code:
mailer.service.ts
:
import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import * as process from 'process';
import { MailerDto } from './mailer.dto';
import { from, Observable, of, Subject, lastValueFrom, share } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import * as EventEmitter from 'events';
@Injectable()
export class MailerService {
private transporter: nodemailer.Transporter;
emailEventEmitter = new EventEmitter();
constructor() {
this.transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: process.env.EMAIL_PORT,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASSWORD,
},
});
}
// Get email sent event stream
getEmailSentStream(): Observable<any> {
return new Observable<any>((observer) => {
// Listen for 'emailSent' event
this.emailEventEmitter.on('emailSent', (data: any) => {
observer.next({ data }); // Send data to SSE
});
}).pipe(share());
}
// Send interview results emails
async sendInterviewResults(mailerDto: MailerDto[]): Promise<void> {
const emailSent$ = new Subject();
Promise.allSettled(
mailerDto.map(async (data: MailerDto) => {
try {
const result = await lastValueFrom(this.sendEmail(data));
emailSent$.next(result);
} catch (error) {
emailSent$.next({ email: data.email, success: false, error });
}
}),
).finally(() => emailSent$.complete());
emailSent$.subscribe((data) => {
this.emailEventEmitter.emit('emailSent', data);
});
}
private sendEmail(
data: MailerDto,
): Observable<{ email: string; success: boolean; error?: any }> {
const { email, username, isPassed } = data;
const mailOptions: nodemailer.SendMailOptions = {
from: `1*******@qq.com`,
to: email,
subject: 'Interview Result Notification',
html: this.generateEmailContent(username, isPassed),
};
return from(this.transporter.sendMail(mailOptions)).pipe(
map(() => ({ email, success: true })),
catchError((error) => {
console.error(`Failed to send interview result email to ${username} (${email}):`, error);
return of({ email, success: false, error });
}),
);
}
private generateEmailContent(username: string, isPassed: boolean): string {
const resultMessage = isPassed
? '???????????? Congratulations, you have passed the interview! ????????????'
: '???????????? We regret to inform you that you did not pass this interview. ????????????';
return `
<div style="font-family: Arial, sans-serif; padding: 20px; border-radius: 5px; background-color: #f5f5f5;">
<h3 style="color: #333;">Dear <span style="color: #007bff;">${username}</span>:</h3>
<p style="font-size: 16px; line-height: 1.5;">${resultMessage}</p>
<p style="font-size: 16px; line-height: 1.5;">Thank you for your interest in our organization!????</p>
<br>
<p style="font-size: 16px; line-height: 1.5;">Sincerely,</p>
<p style="font-size: 16px; line-height: 1.5;">Information Technology Association (ITA)</p>
</div>
`;
}
}
mailer.controller.ts
:
import { Controller, Post, Body, Sse } from '@nestjs/common';
import { MailerService } from './mailer.service';
import { MailerDto } from './mailer.dto';
import { Observable } from 'rxjs';
import { Public } from '../../../utils/jwt/public.decorator';
@Controller('mailer')
export class MailerController {
constructor(private readonly mailerService: MailerService) {}
@Post('inform')
triggerEmails(@Body() mailerDto: MailerDto[]) {
this.mailerService.sendInterviewResults(mailerDto).then(() => {});
}
@Public()
@Sse('email-events')
getEmailEvents(): Observable<any> {
return this.mailerService.getEmailSentStream();
}
}
The problem is twofold:
Connection doesn’t close: Even though the frontend receives all email status updates, the SSE connection remains open indefinitely. I expect the connection to close gracefully after all email statuses have been sent.
Subsequent requests fail silently: When I make subsequent requests to the SSE endpoint, the frontend doesn’t receive any data. However, the backend successfully sends the emails, and the connection closes very quickly (within 10-20 milliseconds), without any errors on either side.
It seems like there might be an issue with how I’m handling the connection lifecycle or event listeners. The first request seems to work partially (data is received), but the connection persists, and subsequent requests are somehow blocked or ignored.
How can I ensure the SSE connection closes automatically after each request and that subsequent requests are handled correctly, delivering all email statuses to the frontend?
Any help in identifying the issue and finding a solution would be greatly appreciated!
The first request to the SSE endpoint seems to work partially. The frontend receives the status updates for each sent email. However, the connection remains open indefinitely, even after all email statuses have been delivered. Subsequent requests to the /mailer/email-events
endpoint don’t deliver any data to the frontend, and the connection closes prematurely without any errors, despite the emails being sent successfully in the backend.
ZK L is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.