How to attach file to an email with nodemailer

前端 未结 8 2090
南笙
南笙 2020-12-04 19:49

I have code that send email with nodemailer in nodejs but I want to attach file to an email but I can\'t find way to do that I search on ne

相关标签:
8条回答
  • 2020-12-04 20:34
    var express = require('express');
    var router = express(),
    multer = require('multer'),
    upload = multer(),
    fs = require('fs'),
    path = require('path');
    nodemailer = require('nodemailer'),
    
    directory = path.dirname("");
    var parent = path.resolve(directory, '..');
    // your path to store the files
    var uploaddir = parent + (path.sep) + 'emailprj' + (path.sep) + 'public' + (path.sep) + 'images' + (path.sep);
    /* GET home page. */
    router.get('/', function(req, res) {
    res.render('index.ejs', {
        title: 'Express'
    });
    });
    
    router.post('/sendemail', upload.any(), function(req, res) {
    
    var file = req.files;
    console.log(file[0].originalname)
    fs.writeFile(uploaddir + file[0].originalname, file[0].buffer,     function(err) {
        //console.log("filewrited")
        //console.log(err)
    })
    var filepath = path.join(uploaddir, file[0].originalname);
    console.log(filepath)
        //return false;
    nodemailer.mail({
        from: "yourgmail.com",
        to: req.body.emailId, // list of receivers
        subject: req.body.subject + " ✔", // Subject line
        html: "<b>" + req.body.description + "</b>", // html body
        attachments: [{
            filename: file[0].originalname,
            streamSource: fs.createReadStream(filepath)
        }]
    });
    res.send("Email has been sent successfully");
    })
    module.exports = router;
    
    0 讨论(0)
  • 2020-12-04 20:46

    If you are passing options object in mail composer constructor and attachment is on http server then it should look like:

    const options = {
        attachments = [
          { // use URL as an attachment
            filename: 'xxx.jpg',
            path: 'http:something.com/xxx.jpg'
          }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题