Nodejs 和 Mailgun:从文件系统发送生成的附件*不是*

Nodejs and Mailgun: Send generated attachment *not* from file system

我在节点应用程序中生成附件,并想使用 Mailgun 发送它们。我无权访问文件系统(Netlify 函数)。

有没有简单的方法可以做到这一点?

孔洞图片

这是一个 Jamstack(Gatsby/React、Netlify、Mailgun)网络应用程序。客户配置和请求报价。浏览器生成 图像并将其发布到 Netlify 函数(获取 api)。该函数发送附有 PDF 报价和图片的报价邮件。

我测试的代码(编辑:02/25)

const path = require('path');
const fs = require('fs');
const mailgun = require('mailgun-js')
const FormData = require('form-data');
const { Readable } = require('stream');

const API_KEY = 'SECRET';
const DOMAIN = 'brasilius.de';

const mg = mailgun({apiKey: API_KEY, domain: DOMAIN, host: "api.eu.mailgun.net"});

const stream = fs.createReadStream('test.txt');                     // This works
/* {
  id: '<20210225115125.1.BF14CC322F8E0DAC@brasilius.de>',
  message: 'Queued. Thank you.'
} */

/*
const stream = Readable.from(["Send this text as attachment."])   // Won't work

{ message: "'from' parameter is missing" }
*/

const data = {
  from: 'Excited User <me@brasilius.de>',
  to: 'test@user.de',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomeness!',
  attachment: stream
};

mg.messages().send(data, (error, body) => {
  console.log(body);
});

我找到的最简单的解决方案here

// https://thecodebarbarian.com/sending-emails-using-the-mailgun-api.html

const mailgun = require('mailgun-js')

const mg = mailgun({apiKey: process.env.API_KEY, domain: process.env.DOMAIN, host: "api.eu.mailgun.net"});

const filename = 'test.txt';
const text = "Example test content."
const attch = new mg.Attachment({data: Buffer.from(text), filename: filename})

const data = {
  from: process.env.FROM,
  to: process.env.TO,
  subject: 'Hello',
  text: 'Testing Mailgun attachments.',
  attachment: attch
};

mg.messages().send(data, (error, body) => {
  console.log(body);
});

正如@Joe 所推荐的,使用 Nodemailers Mailcomposer 的解决方案:

// See: https://documentation.mailgun.com/en/latest/api-sending.html#examples
// See: http://nodemailer.com/extras/mailcomposer/#attachments

const mailgun = require('mailgun-js')
const MailComposer = require('nodemailer/lib/mail-composer');

const mg = mailgun({apiKey: process.env.API_KEY, domain: process.env.DOMAIN, host: "api.eu.mailgun.net"});

const mailOptions = {
  from: process.env.FROM,
  subject: 'Hello',
  text: 'Testing Mailgun attachments.',
  attachments: [
    { // utf-8 string as an attachment
      filename: 'text.txt',
      content: 'For testing just a text file. This could be a ReadStream, Buffer or other.'
    }
  ]
};

const mail = new MailComposer(mailOptions);

mail.compile().build(function(mailBuildError, message) {

  var dataToSend = {
    to: process.env.TO,
    message: message.toString('ascii')
  };

  mg.messages().sendMime(dataToSend, function(sendError, body) {
    if (sendError) {
      console.log(sendError);
      return;
    }
  });
});