All files / server/src/features/notifications email.ts

93.75% Statements 15/16
50% Branches 4/8
100% Functions 3/3
93.75% Lines 15/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                              91x         74x 59x   71x     10x 61x           5x 5x                 15x       10x       74x 74x 74x 73x   73x        
import {
  Transporter,
  createTestAccount,
  createTransport,
  getTestMessageUrl,
} from "nodemailer";
import SMTPTransport from "nodemailer/lib/smtp-transport";
import { config } from "shared/config";
import { EmailMessage } from "server/features/notifications/senderCommon";
 
export class EmailSender {
  private transport:
    | Transporter<SMTPTransport.SentMessageInfo, SMTPTransport.Options>
    | undefined;
  // Used for testing
  private sentMessages: EmailMessage[] = [];
 
  async getTransport(): Promise<
    Transporter<SMTPTransport.SentMessageInfo, SMTPTransport.Options>
  > {
    if (this.transport) {
      return this.transport;
    }
    if (process.env.NODE_ENV === "test") {
      // Tests only assert on the messages handed to the transport, so keep them off
      // the network: the shared test-account service goes down and fails the suite
      this.transport = createTransport({ jsonTransport: true });
    } else Eif (process.env.SETTINGS === "production") {
      this.transport = createTransport({
        host: config.server().emailSMTPHost,
        port: config.server().emailSMTPPort,
      });
    } else {
      const account = await createTestAccount();
      this.transport = createTransport({
        host: config.server().emailSMTPHost,
        port: config.server().emailSMTPPort,
        auth: {
          user: account.user,
          pass: account.pass,
        },
      });
    }
    return this.transport;
  }
 
  getSentEmails(): EmailMessage[] {
    return this.sentMessages;
  }
 
  async sendEmail(message: EmailMessage): Promise<void> {
    const transporter = await this.getTransport();
    const info = await transporter.sendMail(message);
    Eif (process.env.SETTINGS !== "production") {
      this.sentMessages.push(message);
      // eslint-disable-next-line no-console
      console.log(getTestMessageUrl(info));
    }
  }
}