首页 > 解决方案 > 通过 async/await 使用节点邮件程序发送图像

问题描述

如何在 triggerExample.ts 中正确获取 mailOptions?

邮件.ts:

export const sendNewMail = async (html: string, emails: string[]) => {
  let smtpTransport = nodemailer.createTransport({
    service: "Gmail",
    auth: {
      user: "...",
      pass: "...",
    },
  });
  };

triggerExample.ts:

import { sendNewMail  } from "../../mail.ts";

const ordersExample = await getExample();
    ordersExample.forEach(async order => {
      const email = order.sentEmails.email
let html = ` ...
         <img src="cid:image" width="100%" />

`;

      await sendNewMail (html,[email]);

如何正确将此 mailOptions 与 async/await 放在 triggerExample.ts 中:

  var mailOptions = {
    from: "@gmail.com",
    to: emails,
    subject: "subject",
    html: html,
    attachments: [{
      path: __dirname + '/image.jpg',
      cid: 'image' 
  }],
  };
  return smtpTransport.sendMail(
    mailOptions,
    function (error: Error, response: Response) {
      if (error) {
        errors.logError(error);
      } else {
        console.log(`Message sent to ${errors}`);
      }
    }
  );

标签: javascriptnode.jstypescriptasync-awaitnodemailer

解决方案


您似乎了解如何发送电子邮件,也了解如何将图像附加到电子邮件中。您真正不明白的是如何在承诺范围内使用 this ?

为了帮助您更好地理解代码流程及其布局方式,我创建了一个示例,您可以通过添加自己的内容和邮件选项来自定义它,您还可以在必要时将其转换为 typescript:

发送.js:

const nodemailer = require('nodemailer')
const config = {
  port: 'your smtp port',
  host: 'your smtp host',
  user: 'your username',
  pass: 'your password',
  from: {
    name: 'Sender Name',
    email: 'Sender Email Address'
  }
}
module.exports = {
  send(payload) {
    return new Promise(async (resolve, reject) => {
      try {
        const { subject, name, email } = payload
        // The plaintext version
        const text = 'Hello World!'
        // The html version
        const html = '<p>Hello World!</p>'
        // create reusable transporter object using the default SMTP transport
        const transporter = nodemailer.createTransport({
          port: config.port,
          host: config.host,
          auth: {
            user: config.user,
            pass: config.pass
          },
          secure: true
        })
        // setup email options here
        const mailOptions = {
          from: `"${config.from.name}" <${config.from.email}>`, // sender address
          to: `"${name}" <${email}>`, // comma seperated list of receivers
          subject, // Subject line
          text, // plain text body
          html // html body
        }
        // send mail with defined transport object
        const info = await transporter.sendMail(mailOptions)
        // Success
        return resolve(info)
      } catch (err) {
        return reject(err)
      }
    })
  },
};

主.js:

const { send } = require('./send.js');

(async () => {
  try {
    const payload = {
      subject: 'Test Email',
      name: 'Some Person',
      email: 'Their Email Address'
    }
    const info = await send(payload)
    console.log('successfully sent the email:')
    console.log(info)
  } catch (err) {
    console.log('failed to send the email:')
    console.log(err)
  }
})();

在成功的情况下:

{ accepted: [ 'name@domain.tld' ],
  rejected: [],
  envelopeTime: 605,
  messageTime: 596,
  messageSize: 620,
  response:
   '250 Ok someidortheother',
  envelope:
   { from: 'sender@senderdomain.tld',
     to: [ 'name@domain.tld' ] },
  messageId: '<messageidblah@senderdomain.tld>' }

我也可以建议您始终包含电子邮件的纯文本版本,以便它可以在不支持或已配置为不显示 html 正文内容的电子邮件客户端中呈现。


推荐阅读