I'm creating the server with express and want to send mail with QRcode inside the body
var express = require('express');
var app = express();
var nodeMailer = require('nodemailer');
var sql = require("mssql");
var bodyParser = require('body-parser');
var QRCode = require('qrcode')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.post('/send-email', function (req, res) {
QRCode.toDataURL('data invoice untuk di kirim melalui email', function (err, url) {
let data = url.replace(/.*,/,'')
var img = new Buffer(data,'base64')
})
let transporter = nodeMailer.createTransport({
host: 'test',
port: 587,
secure: false,
auth: {
user: 'tes',
pass: 'password'
}
});
let mailOptions = {
from: 'test', // sender address
to: 'test', // list of receivers
subject: 'Test Email Node JS', // Subject line
text: 'Halo ini dari node js', // plain text body
html: 'Halo ini barcodenya </br>' + img // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
//console.log('Message %s sent: %s', info.messageId, info.response);
res.render('index');
});
});
I get an error that img
is not defined.
Variable img
is what the qr code, and for the string it will get the string from SQL query.
Any source for this?
QRCode.toDataURL
is a asynchronous function but your trying to use as synchronously. Use Promises and Async/Await in place of callback function.base64
with image tag
Here are the code snippet changes,
...
app.post('/send-email', async function (req, res) {
let img = await QRCode.toDataURL('data invoice untuk di kirim melalui email');
let transporter = nodeMailer.createTransport({
host: 'test',
port: 587,
secure: false,
auth: {
user: 'tes',
pass: 'password'
}
});
let mailOptions = {
from: 'test', // sender address
to: 'test', // list of receivers
subject: 'Test Email Node JS', // Subject line
text: 'Halo ini dari node js', // plain text body
html: 'Halo ini barcodenya </br> <img src="' + img + '">' // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
//console.log('Message %s sent: %s', info.messageId, info.response);
res.render('index');
});
});
...