Embed image in email body nodemailer nodejs

倾然丶 夕夏残阳落幕 提交于 2019-12-05 18:43:44

问题


I am following the approach used in the nodemailer community site but I cannot seem to get it to work as I am getting the error

   Failed to send email { Error: ENOENT: no such file or directory, open 
'./rello-logo-full-svg.svg'
 errno: -2,
  code: 'ESTREAM',
  syscall: 'open',
  path: './rello-logo-full-svg.svg',
  command: 'API' }

The nodemailer options are as follows

    let mailOptions = {
        from: '<from_email>', 
        to: to_email_address.toString(),
        subject: 'Subject',
        text: 'Hello world', // plain text body
        attachments: [{
          filename: 'rello-logo-full-svg.svg',
          path: './rello-logo-full-svg.svg',
          cid: 'unique@cid'
      }],
        html: emailBody
    };

And in the emailBody variable I have a template string with an image tag line like so

<img style="width:250px;" cid:unique@cid>

Do I maybe need to set the static assets for express or what, the image file is in the same folder as the file that has the above code, any help is appreciated


回答1:


Responding here in case anyone else encounters this! The __dirname above was really helpful, but this is my code to actually see the image embedded in the email

My img tag:

<img src="cid:logo">

My attachments snippet:

attachments: [{
     filename: 'Logo.png',
     path: __dirname +'/folder/Logo.png',
     cid: 'logo' //my mistake was putting "cid:logo@cid" here! 
}]



回答2:


So I got it to work by using ...

 path: __dirname + '/rello-logo-full-svg.svg',

....

But funny this is not what I was trying to achieve because I wanted the image to be in the email body, bu hope this'll help someone else.

Hey, I just changed the file name from .svg to .png, another mistake I made was with the image in the template, I have changed it to

 <img style="width:250px;" src="cid:unique@cid">



回答3:


I found a great example of this at https://community.nodemailer.com/using-embedded-images/. Here is the post

Using Embedded Images

Attachments can be used as embedded images in the HTML body. To use this feature, you need to set additional property of the attachment – cid (unique identifier of the file) which is a reference to the attachment file. The same cid value must be used as the image URL in HTML (using cid: as the URL protocol, see example below).

NB! the cid value should be as unique as possible!

var mailOptions = {
    ...
    html: 'Embedded image: <img src="cid:unique@kreata.ee"/>',
    attachments: [{
        filename: 'image.png',
        path: '/path/to/file',
        cid: 'unique@kreata.ee' //same cid value as in the html img src
    }]
}


来源:https://stackoverflow.com/questions/48449379/embed-image-in-email-body-nodemailer-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!