Sending Templated emails with node.js, node mailer and nodemailer-mailgun-transport - express

I have the following basic nodejs app:
var nodemailer = require('nodemailer');
var hbs = require('nodemailer-express-handlebars');
var options = {
viewEngine: {
extname: '.hbs',
layoutsDir: 'views/email/',
defaultLayout : 'template',
partialsDir : 'views/partials/'
},
viewPath: 'views/email/',
extName: '.hbs'
};
var mg = require('nodemailer-mailgun-transport');
var auth = {
auth: {
api_key: ' mailgun api key ',
domain: ' mailgun email domain '
}
}
var mailer = nodemailer.createTransport(mg(auth));
mailer.use('compile', hbs(options));
mailer.sendMail({
from: 'test#inventori.io',
to: 'test#test.com',
subject: 'Any Subject',
template: 'email.body',
context: {
variable1 : 'value1',
variable2 : 'value2'
}
}, function (error, response) {
// console.error(error);
if (error) {
throw error;
};
console.log('mail sent to ',response);
mailer.close();
});
views/email/template.hbs
{{>email/head}}
<body>
{{>email/header}}
{{{body}}}
{{>email/footer}}
</body>
</html>
views/email/email.body.hbs
<h4>Main Body Here</h4>
{{variable1}} <br/>
{{variable2}}
views/partials/email/header.hbs
<h4>Header Content</h4>
views/partials/email/footer.hbs
<h4>Footer Content</h4>
The handlebars template engine gives zero errors but the mailgun transport throws the following error:
Error: Sorry: template parameter is not supported yet. Check back soon!
at IncomingMessage.<anonymous> (~/test/node_modules/nodemailer-mailgun-transport/node_modules/mailgun-js/lib/request.js:228:15)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
This example uses the gmail node mailer transport:
http://excellencenodejsblog.com/express-nodemailer-sending-mails/
I would like to be able to send templated emails using mailgun.
Any help would be greatly appreciated.
Thank you.

Change your template parameter to html.
If you look at the source code here, the error correct- there is no such thing as a template parameter.

For me, templates weren't rendering properly because I was following an example using extName when the key was actually extname (all lowercase). Perhaps it was renamed overtime and the guide I was looking at is now somewhat out of date.
Full working example below as of 30 May 2020.
Directory Structure:
root/
src/
email-templates/
layouts/
blank.hbs
partials/
hello.hbs
services/
email.service.ts
email.service.ts (Haven't updated this to use proper types yet. Just a poc.)
export async function sendTestEmail() {
try {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
const testAccount = await nodemailer.createTestAccount()
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
})
transporter.use('compile', hbs({
viewEngine: {
extname: '.hbs', // handlebars extension
partialsDir: 'src/email-templates',
layoutsDir: 'src/email-templates/layouts',
defaultLayout: 'blank',
},
viewPath: 'src/email-templates',
extName: '.hbs'
}))
// send mail with defined transport object
const mailOptions = {
from: 'test#gmail.com', // sender address
to: 'test#gmail.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
template: 'hello',
context: {
firstName: 'Clem'
}
}
const info = await transporter.sendMail(mailOptions)
console.log('Message sent: %s', info.messageId)
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
} catch (error) {
console.log(error)
}
}

Related

How can I send multiple emails (around 100) with different email body using amazon ses in NodeJS?

I am trying to send emails to multiple users with email body like
dear {{username}},
/.
....
Your email is {{email}}
...
.
/
how can I do those any ideas, I saw the custom templates for amazon ses but I have 100+ users so how will it be done ?
You can use SES bulk templated emails.
Create a template for your emails.
const AWS = require("aws-sdk");
const ses = new AWS.SES({
accessKeyId: <<YOUR_ACCESS_KEY>>,
secretAccessKey: <<YOUR_ACCESS_KEY>>,
region: <<YOUR_ACCESS_KEY>>
});
const params = {
Template: {
TemplateName: "MyTemplate",
SubjectPart: "Test mail for {{username}}!",
HtmlPart: "<p>Dear {{username}}</p>, <p>Your email is {{email}}.</p>"
}
}
ses.createTemplate(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Once it is done you would see the MyTemplate under Email templates of SES console. We no longer needed template creating part of the code.
Now we can send the email using the following.
const users = [{username:"max", email: "max#m.com"},{username: "mosh", email:"mosh#h.com"}] // sample array of users
let destinations = []
for (const user of users) {
destinations.push({
Destination: {
ToAddresses: [user.email]
},
ReplacementTemplateData: JSON.stringify({
username: user.username, // This will provide the value for username in template
email: user.email // This will provide the value for email in template
})
});
}
const params = {
Source: "sender#xyz.com", // sender email
Template: "MyTemplate", // Template name we have created
Destinations: destinations,
DefaultTemplateData: JSON.stringify({
username: '', // default value for username
email: '' // default value for email
})
}
ses.sendBulkTemplatedEmail(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Make sure you have given the ses:createTemplate and ses:sendBulkTemplatedEmail permissions for the IAM user before running this.
For more info see here.

How to retrive email of specific partner ID that user enters and send it back to controller.

I am having a problem.
I don't know sequelize.js properly.
I have a HTML form as below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Forget Password</title>
</head>
<body>
Forget Password: <br/>
<form action="/forgetpasswordpartner" method="POST">
Enter PartnerID:
<input type="text" name="partnerid">
<button type="submit" value="Send Email">Send Email</button>
</form>
</body>
</html>
I have controller as:
exports.sendresetlinkpartner = function (req, res, next) {
var partnerid = req.body.partnerid;
var token = randomstring.generate({
length: 100,
charset: 'alphanumeric',
capitalization: 'uppercase'
});
var link = "http://localhost:3000/forgetpasswordpartner/" + token;
forgetpasswordmodel.sendresetemailpartner(partnerid, token, function (err, result) {
if (err) throw err;
else {
res.send('Email not found in database');
}
}, function (err, result) {
if (err) throw err;
else {
let transporter = nodemailer.createTransport({
host: 'xxxx',
port:xxx,
secure: false, // true for 465, false for other ports
auth: {
user: 'xxxxxx#xxxx.com', // generated ethereal user
pass: 'xxxxxxxxx' // generated ethereal password
},
//if email is sent via localhost
tls: {
rejectUnauthorized: false
}
});
let mailOptions = {
from: '"xxxxxx" <xxxxxxx#xxxxx.com>', // sender address
to: email, // list of receivers
subject: 'Reset Password', // Subject line
text: 'A password reset for your account was requested', // plain text body
html: "Please click the button below to change your password.<br>" + "<h2>Change your password</h2>" + " "
// html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.send('Couldnot send Reset Password email.Please try again later');
return console.log(error);
}
else {
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
});
res.send('To Change your password, a link has been sent to your email.Check your mail');
}
})
}
And this is my model:
exports.sendresetemailpartner=function(partnerid,token,callback1,callback2){
partner.findOne({where:{'partnerid':partnerid}}).then(partner.update({'token':token},{where:{'companyemail':email}})).then((partner)=>{
if(!partner){
console.log('Email not registered');
callback1();
}
else{
console.log('Token Updated');
callback2();
}
})
I know my model is wrong
What I want is first check whether 'partnerid' exist in database or not and if exist, insert a token in same row record and retrieve email of that partner id and send that emailid back to controller for storing on 'email' variable and sending that mail
Can anyone help me with it.
Use a separate js file for sending email. As the email will be accessed by some other methods too. write it as generic which accepting two parameters.
//utils.js
module.exports = {
sendEmail: function(toEmail, link) {
return new Promise(function(resolve, reject) {
let transporter = nodemailer.createTransport({
host: 'xxxx',
port: xxx,
secure: false, // true for 465, false for other ports
auth: {
user: 'xxxxxx#xxxx.com', // generated ethereal user
pass: 'xxxxxxxxx' // generated ethereal password
},
//if email is sent via localhost
tls: {
rejectUnauthorized: false
}
});
let mailOptions = {
from: '"xxxxxx" <xxxxxxx#xxxxx.com>', // sender address
to: toEmail, // list of receivers
subject: 'Reset Password', // Subject line
text: 'A password reset for your account was requested', // plain text body
html: "Please click the button below to change your password.<br>" + "<h2>Change your password</h2>" + " "
// html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.send('Couldnot send Reset Password email.Please try again later');
//return console.log(error);
reject(error)
} else {
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
resolve("success")
}
});
});
}
}
//Require util.js
import Utils from '../utils'
exports.sendresetlinkpartner = function(req, res, next) {
var partnerid = req.body.partnerid;
var token = randomstring.generate({
length: 100,
charset: 'alphanumeric',
capitalization: 'uppercase'
});
var link = "http://localhost:3000/forgetpasswordpartner/" + token;
partner.findOne({
where: {
'partnerid': partnerid
}
}).then((fetchedPartner) => {
fetchedPartner.update({
token: token
}).then((postUpdate) => {
if (!postUpdate) {
console.log('Email not registered');
} else {
Utils.sendEmail('xyz#gmail.com', link).then((postEmail) => {
// your logic for success
});
}
});
});
}

Send email using Nodemailer with GoDaddy hosted email

I am trying to send an email using nodemailer and a custom email address configured through GoDaddy. Here is a screen shot of the "custom configurations" page in c-panel:
and my code:
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Godaddy',
secureConnection: false,
auth: {
user: 'info#mywebsite.com',
pass: 'mypassword'
}
});
var mailOptions = {
from: 'info#mywebsite.com',
to: 'otheremail#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!',
html: '<h1>Welcome</h1><p>That was easy!</p>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
and my error log:
{ Error: connect EHOSTUNREACH 173.201.192.101:25
at Object.exports._errnoException (util.js:1012:11)
at exports._exceptionWithHostPort (util.js:1035:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)
code: 'ECONNECTION',
errno: 'EHOSTUNREACH',
syscall: 'connect',
address: '173.201.192.101',
port: 25,
command: 'CONN' }
I've tried changing the port number, making it secure vs non-ssl, using my website address as the host, and pretty much everything else I can think of. I have successfully sent an email from the godaddy email using one of the webmail clients. Has anyone else ever encountered this or have recommendations on things to try?
I am trying to send emails using nodemailer from Google Cloud Function using GoDaddy SMTP settings. I do not have Office365 enabled on my GoDaddy hosting. None of the above options worked for me today (12 November 2019). TLS need to be enabled.
I had to use the following configuration:
const mailTransport = nodemailer.createTransport({
host: "smtpout.secureserver.net",
secure: true,
secureConnection: false, // TLS requires secureConnection to be false
tls: {
ciphers:'SSLv3'
},
requireTLS:true,
port: 465,
debug: true,
auth: {
user: "put your godaddy hosted email here",
pass: "put your email password here"
}
});
Then, I could send a test email as follows:
const mailOptions = {
from: `put your godaddy hosted email here`,
to: `bharat.biswal#gmail.com`,
subject: `This is a Test Subject`,
text: `Hi Bharat
Happy Halloween!
If you need any help, please contact us.
Thank You. And Welcome!
Support Team
`,
};
mailTransport.sendMail(mailOptions).then(() => {
console.log('Email sent successfully');
}).catch((err) => {
console.log('Failed to send email');
console.error(err);
});
you should make some changes in your transporter:
var smtpTrans = nodeMailer.createTransport({
service: 'Godaddy',
host: "smtpout.secureserver.net",
secureConnection: true,
port: 465,
auth: {
user: "username",
pass: "password"
}
});
I realize this is an old post, but just wanted to add to this since the GoDaddy SMTP server has changed, just in case someone else comes across this and has the same problem I had. The answer by #tirmey did not work for me, but this did.
let nodemailer = require('nodemailer');
let mailerConfig = {
host: "smtp.office365.com",
secureConnection: true,
port: 587,
auth: {
user: "username#email.com",
pass: "password"
}
};
let transporter = nodemailer.createTransport(mailerConfig);
let mailOptions = {
from: mailerConfig.auth.user,
to: 'SomePerson#email.com',
subject: 'Some Subject',
html: `<body>` +
`<p>Hey Dude</p>` +
`</body>`
};
transporter.sendMail(mailOptions, function (error) {
if (error) {
console.log('error:', error);
} else {
console.log('good');
}
});
Solutions proposed above seem no longer valid, none of them worked for me. Following solution works for me:
const nodemailer = require('nodemailer');
const os = require('os');
let mailerConfig = {
host: os.hostname(),
port: 25,
};
let transporter = nodemailer.createTransport(mailerConfig);
transporter.sendMail({
from: '<from>',
to: '<to>',
subject: '<subject>',
text: '<text>'
}, (err, info) => {
console.log(info);
console.log(err);
});
I could solve the problem by using this code and some points that I brought them after codes:
const smtpTransport = nodemailer.createTransport({
host: "smtp.office365.com",
secure: false,
port: 587,
auth : {
user : 'info#my-domain.com',
pass : 'Password'
}
});
const mailOptions = {
to: 'target-mail#',
subject: 'Test 01',
html: 'Body',
from : 'info#resoluship.com'
};
await smtpTransport.sendMail(mailOptions);
Don't forget to use 'from' attribute in mailOptions
Don't use ',' in your 'from' attribute
For me, the solution for production shared hosting server was completely different than for testing.
It seems no authentication or credentials are required for it to work.
I created this code from this document describing how to use an SMTP relay server. You can use this with nodemailer. GoDaddy support told me I couldn't but I don't think they know about third party tools.
https://au.godaddy.com/help/send-form-mail-using-an-smtp-relay-server-953
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'localhost', //use localhost for linux cPanel hosting
port: 25,
secure: false,
// no need for authentication
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
to: "you#youremail.com", // list of receivers
subject: `New Message from ${name}`, // Subject line
text: `yourtext`, // plain text body
html: `your text in html`, // html body
headers: {
priority: 'high'
},
from: "you#youremail.com" // sender address
});
// send success page if successful
if (res.statusCode === 200) {
res.sendFile(path.join(__dirname, 'views/success.ejs'))
}
console.log("Message sent: %s", info.messageId, res.statusCode);
}
main().catch(console.error);
The most common problem with this error is the antivirus. So disable it for 10 minutes if you are testing it locally.

Setup mailgun with parse-server on Heroku

I am trying to set up mailgun for use with parse-server app on Heroku.
The recommended API is
https://github.com/ParsePlatform/parse-server-simple-mailgun-adapter
But instructions on how to actually achieve this are non existent.
--------- EDIT -----------
Followed instructions and server pushes to Heroku. Though i am still not receiving emails. Im just using mailgun sandbox and have authorised and activated a recipient.
Im not sure about specifying the path to templates or:
fromAddress: process.env.EMAIL_FROM
This wasn't supplied by mailgun so i have just entered no-reply#myservername.heroku
This obviously isnt valid?
index.js code:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var S3Adapter = require('parse-server').S3Adapter;
var path = require('path');
const resolve = require('path').resolve;
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
//**** General Settings ****//
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
maxUploadSize: '500mb',
//**** Security Settings ****//
// allowClientClassCreation: process.env.CLIENT_CLASS_CREATION || false,
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || 'myMasterKey', //Add your master key here. Keep it secret!
//**** Live Query ****//
// liveQuery: {
// classNames: ["TestObject", "Place", "Team", "Player", "ChatMessage"] // List of classes to support for query subscriptions
// },
//**** File Storage ****//
filesAdapter: new S3Adapter({
accessKey: process.env.S3_ACCESS_KEY || '',
secretKey: process.env.S3_SECRET_KEY || '',
bucket: process.env.S3_BUCKET || '',
directAccess: true
}),
//**** Email Verification ****//
/* Enable email verification */
// verifyUserEmails: true,
/* The public URL of your app */
// This will appear in the link that is used to verify email addresses and reset passwords.
publicServerURL: process.env.SERVER_URL || '',
appName: process.env.APP_NAME || '',
emailAdapter: {
module: 'parse-server-mailgun',
options: {
fromAddress: process.env.EMAIL_FROM || '',
domain: process.env.MAILGUN_DOMAIN || '',
apiKey: process.env.MAILGUN_API_KEY || '',
templates: {
passwordResetEmail: {
subject: 'Reset your password',
pathPlainText: resolve(__dirname, 'https:/myparseserveronheroku.herokuapp.com/node_modules/parse-server-mailgun-adapter/test/email-templates/password_reset_email.txt'),
pathHtml: resolve(__dirname, 'https:/myparseserveronheroku.herokuapp.com/node_modules/parse-server-mailgun-adapter/test/email-templates/password_reset_email.html'),
callback: (user) => { return { firstName: user.get('firstName') }}
// Now you can use {{firstName}} in your templates
},
verificationEmail: {
subject: 'Confirm your account',
pathPlainText: resolve(__dirname, 'https:/myparseserveronheroku.herokuapp.com/node_modules/parse-server-mailgun-adapter/test/email-templates/verification_email.txt'),
pathHtml: resolve(__dirname, 'https:/myparseserveronheroku.herokuapp.com/node_modules/parse-server-mailgun-adapter/test/email-templates/verification_email.html'),
callback: (user) => { return { firstName: user.get('firstName') }}
// Now you can use {{firstName}} in your templates
}
}
}
}
});
My swift code to send password reset says that the message has been sent, so i assume that everything Cliff has told me is correct and the server side is set up ok, probably just something stupid that i have done with the variables.
PFUser.requestPasswordResetForEmail(inBackground: emailAddress!) { (success, error) in
if error != nil {
// display error message
let userMessage: String = error!.localizedDescription
GeneralFunctions.createAlert(errorTitle: "Oops...", errorMessage: userMessage, className: self )
} else {
// display success message
let userMessage: String = "An new password was sent to \(emailAddress!)"
GeneralFunctions.createAlert(errorTitle: "Hooray...", errorMessage: userMessage, className: self )
}
}
----------- EDIT ----------
Verbose log after trying reset password
email=my-verified-email#email.com.au
2017-02-06T00:44:25.788619+00:00 app[web.1]: [36mverbose[39m: RESPONSE from [POST] /parse/requestPasswordReset: {
2017-02-06T00:44:25.788623+00:00 app[web.1]: "response": {}
2017-02-06T00:44:25.788625+00:00 app[web.1]: }
2017-02-06T00:44:25.797455+00:00 app[web.1]: { Error: ENOENT: no such file or directory, open '/app/https:/myparseserveronheroku.herokuapp.com/node_modules/parse-server-mailgun-adapter/test/email-templates/password_reset_email.txt'
2017-02-06T00:44:25.797458+00:00 app[web.1]: errno: -2,
2017-02-06T00:44:25.797459+00:00 app[web.1]: code: 'ENOENT',
2017-02-06T00:44:25.797459+00:00 app[web.1]: syscall: 'open',
2017-02-06T00:44:25.797462+00:00 app[web.1]: path: '/app/https:/myparseserveronheroku.herokuapp.com/node_modules/parse-server-mailgun-adapter/test/email-templates/password_reset_email.txt' }
2017-02-06T00:44:25.792191+00:00 heroku[router]: at=info method=POST path="/parse/requestPasswordReset" host=myparseserveronheroku.herokuapp.com request_id=666ff3e0-db4a-4e76-b7b5-6353edc7e15a fwd="111.111.111.11" dyno=web.1 connect=0ms service=81ms status=200 bytes=483
So definitely looks like its trying to send from a template that doesn't exist. Im not sure how to specify path here, i had thought that all these directories including node_modules/parse-server-mailgun-adapter/test/email-templates were pushed to Heroku.
First:
npm install --save parse-server-mailgun
Then in your index.js file you can set it up as follows in the initialize:
publicServerURL: 'http://MY_HEROKU_APP.herokuapp.com/parse',
appName: 'MY_APP',
emailAdapter: {
module: 'parse-server-mailgun',
options: {
fromAddress: 'no-reply#example.com',
domain: 'example.com',
apiKey: 'key-XXXXXX',
}
}
The default Mailgun adapter that comes with the Parse Server, you need to set a fromAddres, and the domain and apiKey provided by Mailgun. In addition, you also need to configure the templates you want to use. You must provide at least a plain-text version for each template. The html versions are optional.
verifyUserEmails: true,
emailAdapter: {
module: 'parse-server-mailgun',
options: {
// The address that your emails come from
fromAddress: 'YourApp <noreply#yourapp.com>',
// Your domain from mailgun.com
domain: 'example.com',
// Your API key from mailgun.com
apiKey: 'key-mykey',
// The template section
templates: {
passwordResetEmail: {
subject: 'Reset your password',
pathPlainText: resolve(__dirname, 'path/to/templates/password_reset_email.txt'),
pathHtml: resolve(__dirname, 'path/to/templates/password_reset_email.html'),
callback: (user) => { return { firstName: user.get('firstName') }}
// Now you can use {{firstName}} in your templates
},
verificationEmail: {
subject: 'Confirm your account',
pathPlainText: resolve(__dirname, 'path/to/templates/verification_email.txt'),
pathHtml: resolve(__dirname, 'path/to/templates/verification_email.html'),
callback: (user) => { return { firstName: user.get('firstName') }}
// Now you can use {{firstName}} in your templates
},
customEmailAlert: {
subject: 'Urgent notification!',
pathPlainText: resolve(__dirname, 'path/to/templates/custom_alert.txt'),
pathHtml: resolve(__dirname, 'path/to/templates/custom_alert.html'),
}
}
}
Reference to the NPM package: https://www.npmjs.com/package/parse-server-mailgun

Nodemailer attachment not working in nodemailer 0.7.1

I am trying to send an attachment using nodemailer 0.7.1. The attachment is sent fine but when I try to open it, the shows ERROR OPENING FILE.
Here is my code:
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);
}
});
Any suggestion on how to resolve this would be of great help.
Replace the filename and filePath lines with path: './result/results.txt' and try.
Try this code.First you have to create an app in Google Cloud Console and Enable Gmail API from library.Get the credentials of your app.For that click on Credentials and in the place of Authorized redirect URIskeep this link https://developers.google.com/oauthplayground and save it.Next in another tab open this link https://developers.google.com/oauthplayground/ click on settings symbol on right side.And make a tick on check box(i.e,Use your own OAuth credentials) after this You have to give your clientId and clientSecret.And at the sametime on left side there is a text box with placeholder like Input Your Own Scopes there keep this link https://mail.google.com/ and click on Authorize APIs then click on Exchange authorization code for tokens then you will get your refreshToken and accessToken keep these two in your code.Hope thsi helps for you..
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');
}
})
});