Nodemailer附件在nodemailer 0.7.1中不起作用

时间:2016-08-26 10:35:30

标签: npm nodemailer

我正在尝试使用nodemailer 0.7.1发送附件。附件发送正常,但是当我尝试打开它时,显示ERROR OPENING FILE。

这是我的代码:

var nodemailer = require("nodemailer");

var transport = nodemailer.createTransport("SMTP", {
    host: "smtp.gmail.com", // hostname
    secureConnection: true, // use SSL
    port: <port>, // port for secure SMTP
    auth: {
        user: "example.example@gmail.com",
        pass: "password"
    }
});

console.log("SMTP Configured");

var mailOptions = {
    from: 'example.sender@gmail.com', // sender address
    to: 'example.receiver@gmail.com', // list of receivers
    subject: 'Report for Test Result', // Subject line
    text: 'Contains the test result for the test run in html file', // plaintext body
    attachments: [
        {
            'filename': 'results.txt',
            'filePath': './result/results.txt',
        }

    ]
};
transport.sendMail(mailOptions, function (error, response) {
    if (error) {
        console.log(error);
    } else {
        console.log("Message sent: " + response.message);
    }

});

任何关于如何解决这个问题的建议都会有很大的帮助。

2 个答案:

答案 0 :(得分:0)

filenamefilePath行替换为path: './result/results.txt'并尝试。

答案 1 :(得分:0)

尝试此代码。首先,您必须在Google云端控制台中创建应用并从库中启用Gmail API。获取应用的凭据。点击凭据并在授权重定向URI的位置保持此链接{{3然后在另一个标签中打开此链接,打开此链接https://developers.google.com/oauthplayground点击右侧的设置符号。勾选复选框(即使用您自己的OAuth凭据)之后您必须提供您的clientId和clientSecret.And在左侧的同一时间有一个带有占位符的文本框,如输入您自己的范围,保留此链接https://developers.google.com/oauthplayground/并单击授权API然后单击代币的Exchange授权代码然后您将获得您的refreshToken和accessToken将这两个保存在你的代码中。希望这对你有帮助..

const nodemailer=require('nodemailer');
const xoauth2=require('xoauth2');
var fs=require('fs');
var transporter=nodemailer.createTransport({
service:'gmail',
auth:{
    type: 'OAuth2',
    user:'Sender Mail',
clientId:'Your_clientId',//get from Google Cloud Console
clientSecret:'Your clientSecret',//get from Google Cloud Console
refreshToken:'Your refreshToken',//get from  https://developers.google.com/oauthplayground
accessToken:'Tor accessToken'//get from  https://developers.google.com/oauthplayground
},
});
fs.readFile("filePath",function(err,data){
var mailOptions={
from:' <Sender mail>',
to:'receiver mail',
subject:'Sample mail',
text:'Hello!!!!!!!!!!!!!',
attachments:[
{
    'filename':'filename.extension',//metion the filename with extension
     'content': data,
     'contentType':'application/type'//type indicates file type like pdf,jpg,...
}]
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
    console.log('Error');
}
else{
console.log('Email Sent');
}
})
});