1. Install dependencies

npm install nodemailer
Copy the code

Two, use method

const nodemailer = require('nodemailer');

async send({ to, subject, text, html, filename, path, headers }) {
  const config = {
    user: ' '.// email
    pass: ' '.// If the qq mailbox is used, the SMTP authorization code is used
  };

  const transporter = nodemailer.createTransport({
    host: 'smtp.163.com'.secureConnection: true.port: 465.secure: true.auth: {
      user: config.user,
      pass: config.pass,
    },
  });

  const mailOptions = {
    from: config.user,
    to,
    subject,
    text,
    html,
    attachments: [{
      filename,
      path,
    }],
    headers,
  };

  return await transporter.sendMail(mailOptions, (error, data) = > {
    transporter.close();
    if (error) {
      return console.log(error);
    }
    return data;
  });
}
Copy the code

Nodemailer sometimes reports a 554 error because the content of the message sent contains unauthorized information or is identified by the system as spam.

Solution: Write the subject and text parameters realistically, without the usual text such as’ test ‘, and add headers parameters to avoid 554 errors.

In addition, during the deployment, it was found that 163’s account occasionally had network problems when sending emails. As a result, it could be seen that the emails were successfully sent but could not be received in the console. Recommended to use QQ SMTP service, more stable than 163.

await this.service.email.send({
  to: query.email,
  subject: `subject`.text: `text`.filename: 'studyData.zip'.path: filepath,
  headers: {
    time: new Date().getTime(),
  },
});
Copy the code