I would like to simplify sending html-messages with Nodemailer by using messages stored as html-files instead of "hard-coded" message strings. However, for some reason Nodemailer does not work as I would expect it to do.
The following code works perfectly fine (version with "hard-coded" message string):
const nodemailer = require('nodemailer');
const fs = require('fs');
let htmlMessage = "";
// Retrieve message from file
fs.readFile("./Message.html", 'utf8', (err, data) => {
if (err) throw err;
console.log(data)
htmlMessage = data;
});
console.log(htmlMessage);
// 1.) Define "transporter"
const transporter = nodemailer.createTransport({
service: ...,
auth: {
user: ...,
pass: ...
}
})
// 2.) Configure email
const email = {
from: ...,
text: 'This is a test! (Plain Text)',
// html: htmlMessage
html: '<div style="margin: 1em; padding: 0.5em; background-color: rgb(90, 168, 90); font-size: 1.5em; '
+ 'border-radius: 0.5em; font-family: Arial, Helvetica, sans-serif;"> '
+ 'This is a test!'
+ '</div>'
};
// 3.) Send email
transporter.sendMail(email, (error, info) => { if (error) {
console.error(error); } else {
console.log('Message sent: %s', info.messageId); }
});
However, if I change the message like this ...
// 2.) Configure email
const email = {
from: ...,
text: 'This is a test! (Plain Text)',
html: htmlMessage
/*
html: '<div style="margin: 1em; padding: 0.5em; background-color: rgb(90, 168, 90); font-size: 1.5em; '
+ 'border-radius: 0.5em; font-family: Arial, Helvetica, sans-serif;"> '
+ 'This is a test!'
+ '</div>'
*/
};
... and replace the "hard-coded" string with this file ...
Message.html
<div style="margin: 1em;
padding: 0.5em;
background-color: rgb(90, 168, 90);
font-size: 1.5em;
border-radius: 0.5em;
font-family: Arial, Helvetica, sans-serif;">
This is a test!
</div>
... sending the html content does not work any more. I am only receiving the "plain text version". For some reason Nodemailer fails. What am I doing wrong?