How to attach file to an email with nodemailer

前端 未结 8 2089
南笙
南笙 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:23

    Include in the var mailOption the key attachments, as follow:

    var mailOptions = {
    ...
    attachments: [
        {   // utf-8 string as an attachment
            filename: 'text1.txt',
            content: 'hello world!'
        },
        {   // binary buffer as an attachment
            filename: 'text2.txt',
            content: new Buffer('hello world!','utf-8')
        },
        {   // file on disk as an attachment
            filename: 'text3.txt',
            path: '/path/to/file.txt' // stream this file
        },
        {   // filename and content type is derived from path
            path: '/path/to/file.txt'
        },
        {   // stream as an attachment
            filename: 'text4.txt',
            content: fs.createReadStream('file.txt')
        },
        {   // define custom content type for the attachment
            filename: 'text.bin',
            content: 'hello world!',
            contentType: 'text/plain'
        },
        {   // use URL as an attachment
            filename: 'license.txt',
            path: 'https://raw.github.com/andris9/Nodemailer/master/LICENSE'
        },
        {   // encoded string as an attachment
            filename: 'text1.txt',
            content: 'aGVsbG8gd29ybGQh',
            encoding: 'base64'
        },
        {   // data uri as an attachment
            path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
        }
    ]
    

    }

    Choose the option that adjust to your needs.

    Link:Nodemailer Repository GitHub

    Good Luck!!

    0 讨论(0)
  • 2020-12-04 20:23

    Just look at here. Nodemailer > Message configuration > Attachments

    The code snippet is below (pdfkit gets the stream):

    // in async func
    pdf.end();
    const stream = pdf;
    const attachments = [{ filename: 'fromFile.pdf', path: './output.pdf', 
    contentType: 'application/pdf' }, { filename: 'fromStream.pdf', content: stream, contentType: 'application/pdf' }];
    await sendMail('"Sender" <sender@test.com>', 'reciver@test.com', 'Test Send Files', '<h1>Hello</h1>', attachments);
    

    Stream uses content not streamSource This bothered me before, share with everyone :)

    0 讨论(0)
  • 2020-12-04 20:24
    var mailer = require('nodemailer');
    mailer.SMTP = {
        host: 'host.com', 
        port:587,
        use_authentication: true, 
        user: 'you@example.com', 
        pass: 'xxxxxx'
    };
    
    Then read a file and send an email :
    
    fs.readFile("./attachment.txt", function (err, data) {
    
        mailer.send_mail({       
            sender: 'sender@sender.com',
            to: 'dest@dest.com',
            subject: 'Attachment!',
            body: 'mail content...',
            attachments: [{'filename': 'attachment.txt', 'content': data}]
        }), function(err, success) {
            if (err) {
                // Handle error
            }
    
        }
    });
    
    0 讨论(0)
  • 2020-12-04 20:26

    I've tested each of these attachments methods and none is ok for me. Here's my mailer function code without the smtp transport config :

    function mailer(from, to, subject, attachments, body) {
    
        // Setup email
        var mailOptions = {
            from: from,
            to: to,
            subject: subject,
            attachments: attachments,
            html: body
        };
    
        // send mail with defined transport object
        smtpTransport.sendMail(mailOptions, function(error, response){
            if(error) console.log(error);
            else console.log("Message sent: " + response.message);
            // shut down the connection pool, no more messages
            smtpTransport.close();
        });
    }
    

    And then the call :

    var attachments = [{ filename: 'test.pdf', path: __dirname + '/pdf/test.pdf', contentType: 'application/pdf' }];
    mailer("exped@gmail.com", "mymail@gmail.com", "Test", attachments, "<h1>Hello</h1>");
    

    The mail comes successfully but with no attachment. Even if I set a string or buffer attachment it's the same result.

    0 讨论(0)
  • 2020-12-04 20:26

    The alternative solution is to host your images online using a CDN and link to the online image source in your HTML, eg. <img src="list_image_url_here">.

    (I had problems with nodemailer's image embedding using nodemailer version 2.6.0, which is why I figured out this workaround.)

    An added benefit of this solution is that you're sending no attachments to nodemailer, so the sending process is more streamlined.

    0 讨论(0)
  • 2020-12-04 20:34

    Your code is almost right, just need to add, "attachments" property for attaching the files in your mail,

    YOUR mailOption:

    var mailOption = {
            from: from,
            to:  to,
            subject: subject,
            text: text,
            html: html
    }
    

    Just add attachments like

    var mailOption = {
            from: from,
            to:  to,
            subject: subject,
            text: text,
            html: html,
            attachments: [{
                filename: change with filename,
                path: change with file path
            }]
    }
    

    attachments also provide some other way to attach file for more information check nodemailer community's documentation HERE

    0 讨论(0)
提交回复
热议问题