nodemailer#Transporter TypeScript Examples

The following examples show how to use nodemailer#Transporter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Arbitrageur.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private async mailNotify(title: string, message: string): Promise<void> {
        if (!this.serverProfile.emailUser || !this.serverProfile.emailPass){
            return
        }

        const nowTime = Date.now()
        if (nowTime - this.emailEventMap[title] < 300000){
            return
        }
        this.emailEventMap[title] = nowTime
 
        let transporter: Transporter = nodemailer.createTransport({
            host: this.serverProfile.emailHost,
            port: Number(this.serverProfile.emailPort),
            // secure: false, // true for 465, false for other ports
            auth: {
              user: this.serverProfile.emailUser, // generated ethereal user
              pass: this.serverProfile.emailPass, // generated ethereal password
            },
        })
    
        let info = await transporter.sendMail({
            from: ` ${title} <${this.serverProfile.emailUser}>`, 
            to: this.serverProfile.emailTo, 
            subject: "SakePerp-Arbitrageur",
            text: message, 
            html: message, 
        });
           
        this.log.jinfo({
            event: "mailNotify",
            title: title,
            message: message,
            id: info.messageId,
        })
    }
Example #2
Source File: build.ts    From payload with MIT License 6 votes vote down vote up
async function handleTransport(transport: Transporter, email: EmailTransport, logger: Logger): BuildEmailResult {
  try {
    await transport.verify();
  } catch (err) {
    logger.error(
      'There is an error with the email configuration you have provided.',
      err,
    );
  }

  return { ...email, transport };
}
Example #3
Source File: build.ts    From payload with MIT License 6 votes vote down vote up
export default async function buildEmail(emailConfig: EmailOptions, logger: Logger): BuildEmailResult {
  if (hasTransport(emailConfig) && emailConfig.transport) {
    ensureConfigHasFrom(emailConfig);
    const email = { ...emailConfig };
    const { transport } : {transport: Transporter} = emailConfig;
    return handleTransport(transport, email, logger);
  }

  if (hasTransportOptions(emailConfig) && emailConfig.transportOptions) {
    ensureConfigHasFrom(emailConfig);
    const email = { ...emailConfig } as EmailTransport;
    const transport = nodemailer.createTransport(emailConfig.transportOptions);
    return handleTransport(transport, email, logger);
  }

  return handleMockAccount(emailConfig, logger);
}
Example #4
Source File: EtherealMailProvider.ts    From gobarber-api with MIT License 5 votes vote down vote up
private client: Transporter;
Example #5
Source File: SESMailProvider.ts    From gobarber-api with MIT License 5 votes vote down vote up
private client: Transporter;
Example #6
Source File: EtherealMailProvider.ts    From hotseat-api with MIT License 5 votes vote down vote up
private client: Transporter;
Example #7
Source File: SESMailProvider.ts    From hotseat-api with MIT License 5 votes vote down vote up
private client: Transporter;
Example #8
Source File: MailtrapProvider.ts    From umbriel with MIT License 5 votes vote down vote up
private transporter: Transporter
Example #9
Source File: EtherealMailProvider.ts    From gobarber-project with MIT License 5 votes vote down vote up
private client: Transporter;
Example #10
Source File: SESMailProvider.ts    From gobarber-project with MIT License 5 votes vote down vote up
private client: Transporter;
Example #11
Source File: EtherealMailProvider.ts    From GoBarber with MIT License 5 votes vote down vote up
private transporter: Transporter;
Example #12
Source File: SESMailProvider.ts    From GoBarber with MIT License 5 votes vote down vote up
private transporter: Transporter;
Example #13
Source File: mailer.service.ts    From rest-api.ts with MIT License 5 votes vote down vote up
private static transporter: Transporter;
Example #14
Source File: EmailFactory.ts    From ZenTS with MIT License 5 votes vote down vote up
protected transporter: Transporter
Example #15
Source File: create-transport.ts    From server with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a Mail Transporter using Node mailer
 *
 * @param {ISMTPProviderDoc} SMTPProvider - SMTP Provider Document from Database
 * @param {ISMTPMailerDoc} SMTPMailer - SMTP Mailer Document from Database
 * @param {IGMAILOptions} gmailOptions - GMAIL Credential Document from Database
 * @returns {Transporter} - Nodemailer Transporter
 */
export default function (
  SMTPProvider: ISMTPProviderDoc,
  SMTPMailer: ISMTPMailerDoc,
  gmailOptions?: IGMAILOptions,
): Transporter {
  const transporterOptions:
    | SMTPPool
    | SMTPPool['options']
    | SMTPTransport
    | SMTPTransport['options'] = {
    host: SMTPProvider.smtp.url,
    port: SMTPProvider.smtp.port,
    pool: true,
    secure: true,
    auth: {
      user: SMTPMailer.email,
      pass: SMTPMailer.password,
    },
  };
  if (SMTPProvider.dkim_key && SMTPProvider.dkim_options) {
    transporterOptions.dkim = {
      privateKey: SMTPProvider.dkim_key,
      domainName: SMTPProvider.dkim_options.domain,
      keySelector: SMTPProvider.dkim_options.key_selector,
    };
  }
  if (SMTPProvider.type === 'gmail' && gmailOptions) {
    if (gmailOptions.type === 'normal') {
      transporterOptions.auth = {
        ...transporterOptions.auth,
        type: 'OAUTH2',
        clientId: gmailOptions.credentials.client_id,
        clientSecret: gmailOptions.credentials.client_secret,
        refreshToken: gmailOptions.tokens.refresh.token,
        accessToken: gmailOptions.tokens.access.token,
        expires: gmailOptions.tokens.access.expires_at,
      };
    } else if (
      gmailOptions.type === 'service' &&
      gmailOptions.service_account
    ) {
      transporterOptions.auth = {
        ...transporterOptions.auth,
        type: 'OAUTH2',
        user: gmailOptions.service_account.client.email,
        serviceClient: gmailOptions.service_account.client.id,
        privateKey: gmailOptions.service_account.private_key.key,
        accessToken: gmailOptions.tokens.access.token,
        expires: gmailOptions.tokens.access.expires_at,
      };
    } else {
      throw new Error(
        'Configuration is Wrong, Please pass Parameters Carefully Again',
      );
    }
  } else if (SMTPProvider.type === 'gmail' && !gmailOptions) {
    throw new Error(
      'GmailOptions is Necessary if SMTP is of Type Gmail, Please pass the Gmailoptions',
    );
  }
  const transporter = createTransport(transporterOptions);
  return transporter;
}
Example #16
Source File: setupCronTask.ts    From one-platform with MIT License 4 votes vote down vote up
setupCronTask = (
  jobs: Agenda,
  logger: Logger,
  config: Config,
  mailer: Transporter<SMTPTransport.SentMessageInfo>,
) => {
  /**
   * This is the parent task which runs exactly 12am
   * It goes through all env and spin up another queue called child with required data
   */
  jobs.define(Jobs.SUBSCRIPTION_PARENT, { concurrency: 1 }, async () => {
    logger.info('Cron task for subscriptions started');

    const totalNamespace = await Namespace.count();
    const perDoc = 20;
    const numberOfCycles = Math.ceil(totalNamespace / perDoc);

    for (let i = 1; i <= numberOfCycles; i += 1) {
      const nsDocs = await Namespace.find()
        .sort([['createdOn', -1]])
        .limit(perDoc)
        .skip(perDoc * (i - 1))
        .lean();
      nsDocs.forEach((doc) => {
        doc.schemas.forEach((schema) => {
          if (schema.flags.isDeprecated) return;

          schema.environments.forEach((env) => {
            if (!env.schemaEndpoint) {
              return;
            }

            jobs.now(Jobs.SUBSCRIPTION_CHILD, {
              namespace: { id: doc._id, name: doc.name },
              schema: { id: schema._id, name: schema.name, category: schema.category },
              env,
            });
          });
        });
      });
    }

    logger.info('Cron task for subscriptions ended');
  });

  /**
   * Child process that handles diff finding and mailing
   */
  jobs.define(Jobs.SUBSCRIPTION_CHILD, { concurrency: 10 }, async (job: Job) => {
    logger.info(`triggered job: ${job.attrs._id}`);
    const { data } = job.attrs;

    if (!data) return;

    const { namespace, schema, env } = data;
    const subLog = logger.child({
      namespace: namespace.id,
      schema: schema.id,
      envId: env._id,
      name: env.name,
    });
    const headers = env?.headers?.map(({ key, value }: { key: string; value: string }) => ({
      key,
      value: decrypt(config.decryptionKey, value),
    }));

    const res = await fetchSchema(data.schema.category, env.schemaEndpoint, headers);

    const resBase64 = Buffer.from(res).toString('base64');

    const store = await SpecStore.findOne({
      namespaceId: namespace.id,
      schemaId: schema.id,
      environmentId: env._id,
    })
      .sort([['createdOn', -1]])
      .lean();

    /**
     * Spec is not added, therefore not needed to do any furthur process
     * Just store it
     */
    if (!store) {
      subLog.info('API not added yet');
      await saveSpecSheet(namespace.id, schema.id, env._id, resBase64);
      return;
    }

    const oldSpec = Buffer.from(store.spec, 'base64').toString();

    /**
     * Check for graphql API
     * Using inspector compare two schemas
     * If there is a change store new schema
     * Send mail with new changes denoted
     */
    if (data.schema.category === IApiCategory.Graphql) {
      try {
        const gqlDiff = await diffGraphql(oldSpec, res);

        if (!gqlDiff.hasChanged) {
          subLog.info('GQL API not changed');
          return;
        }

        subLog.info('GQL API changed');
        await saveSpecSheet(namespace.id, schema.id, env._id, resBase64);

        const subscribers = await getSubscribersOfAnEnv(namespace.id, schema.id, env._id);
        if (!subscribers.length) {
          subLog.info('No subscribers found!!!');
          return;
        }

        await mailer.sendMail({
          from: 'One Platform | API Catalog<[email protected]>',
          to: subscribers.map((el) => el.subscriberEmail),
          subject: `API updates for ${env.name.toUpperCase()} environment of
            ${schema.name.toUpperCase()} in ${namespace.name.toUpperCase()} namespace`,
          html: gqlApiTemplate({
            ...gqlDiff,
            namespace: namespace.name,
            schema: schema.name,
            environment: env.name,
          }),
        });

        subLog.info('Mail send to subscribers');
      } catch (error) {
        subLog.error(error?.message);
      }
      return;
    }

    /**
     * Else case: REST API
     * Check for openapi difference
     * Send mail to subscribers of any change classified into breaking and non breaking
     */
    try {
      const diff = await diffOpenAPI(oldSpec, res);

      if (!diff.hasChanged) {
        subLog.info({ name: env.name }, 'Rest API not changed');
        return;
      }

      subLog.info('REST API changed');

      await saveSpecSheet(namespace.id, schema.id, env._id, resBase64);
      const subscribers = await getSubscribersOfAnEnv(namespace.id, schema.id, env._id);
      if (!subscribers.length) {
        subLog.info('No subscribers found!!!');
        return;
      }

      await mailer.sendMail({
        from: 'One Platform | API Catalog<[email protected]>',
        to: subscribers.map((el) => el.subscriberEmail),
        subject: `API updates for ${env.name.toUpperCase()} environment of
            ${schema.name.toUpperCase()} in ${namespace.name.toUpperCase()} namespace`, // Subject line
        html: restApiTemplate({
          ...diff,
          namespace: namespace.name,
          schema: schema.name,
          environment: env.name,
        }),
      });
      subLog.info('Mail send');
    } catch (error) {
      subLog.error(error);
    }
  });

  jobs.on(`fail:${Jobs.SUBSCRIPTION_CHILD}`, (err, job: Job) => {
    logger.error(`Failed to execute job: ${job.attrs._id}`);
    logger.error(job.attrs.data?.env?.name);
    logger.error(err);
  });

  jobs.start();
  jobs.on('ready', async () => {
    await jobs.every('0 1 * * *', Jobs.SUBSCRIPTION_PARENT);
  });
}