如何使用Mailgun和Node.js发送图片附件?

4
我��在尝试将图片作为电子邮件的附件发送,但我无法弄清如何完成此操作。
我使用Mailgun发送邮件,Cloudinary上传图像,MongoDB作为我的数据库,并使用Node.js/Express作为后端。
用户流程如下:
- 用户通过网站提交图片 - 图片通过Cloudinary��传,并直接保存每个图像的链接到MongoDB数据库中 - 通过Mailgun发送邮件,通知���户有新帖子,并在正文中提供图像链接
显然,这不是理想的方式,因为需要逐个点击每个链接才能查看和下载图像。我想直接将它们附加到电子邮件中,以便用户更轻松地下载图像。
我已查看了Mailgun的文档,但似乎不能将非本地图像作为附件发送。我有什么遗漏的吗?
我尝试使用Mailgun的'inline'和'attachment'参数,但最终出现了错误消息,指出无法找到文件/目录。
var pictures = [];
        post.images.forEach(function(photos){
            pictures.push(photos + " ");
            return pictures;
        });

var attch = new mailgun.Attachment({data: pictures[0], filename: "picture"});
        var data = {
            from: "email <email@email.com>",
            to: "email@email.com",
            subject: 'this is an email',
            html: 'here is a new post and here are the images in that post',
            attachment: attch
        };

期望的结果是一封带有新帖子附带图片的电子邮件,或者在这种情况下,来自该帖子的单个图片。

实际结果是出现了以下错误信息:

events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: ENOENT: no such file or directory, stat 'https://res.cloudinary.com/user/image/upload/image.jpg '

如果您有图像URL并且它是公共的,则可以在HTML正文中显示图像。还有另一种选择,您可以将图像下载到本地/tmp目录,然后将图像URL传递给附件密钥: attachment:['/tmp/abc.png','/tmp/xyz.jpg'] - Sayed Tauseef Haider Naqvi
2个回答

9

mailgun.js 包可以接受文件路径、缓冲区和流作为附件。如果要从外部 URL 附加您的图片,请使用流。

var request = require('request');
var image = request(pictures[0]);
var data = {
    from: "email <email@email.com>",
    to: "email@email.com",
    subject: 'this is an email',
    html: 'here is a new post and here are the images in that post',
    attachment: image
};

这里是来自mailgun.js的示例代码:

var request = require('request');
var file = request("https://www.google.ca/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");

var data = {
  from: 'Excited User <me@samples.mailgun.org>',
  to: 'serobnic@mail.ru',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomeness!',
  attachment: file
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

参考:https://www.npmjs.com/package/mailgun-js#attachments

该链接是关于mailgun-js的附件功能的文档。

@JordanPisani,你能让它在多张图片上运行吗? - jhk
@jhk 是的,请参考这个主题 - Jordan Pisani

0

使用 axios 和多个文件

const downloadFile = (link: Link) =>
  axios.get(link, {
    responseType: 'stream', // Important
  });

const files = fileLinks // example: ["http://example.com/1.png", "http://example.com/2.png"]
   .map((link) => downloadFile(link))
   .map((response) => response.data)


const data = {
  from: 'Template from <my@email.com>',
  to: 'target@email.com',
  subject: 'Title',
  text: 'Test text',
  attachment: files 
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接