Search code examples
javascriptnode.jsnodemailer

Nodemailer does not send the text with line breaks


I am using Nodemailer which is a NodeJS module for sending mails. However, it does not send the mails with line breaks but I have tried to print out the variable that contains the text I am trying to send and there are line breaks.

I get the text I write in a text area:

enter image description here

site.js:

$("#send-mail").click(function(){
    $.post("/sendMail",{fieldHeader: $('#field-header').val()}, function(data){
        window.location.href ="/";
    });
});

server.js:

app.post('/sendMail', function(req, res) {
    mailSender.init(req.body.fieldHeader);
});

mailSender.js

function init(fieldHeader) {
    console.log(fieldHeader);
    if(fieldHeader!=null) {
        var mailer = require("nodemailer");

        var smtpTransport = mailer.createTransport({
            host: "smtp.gmail.com",
            service: "Gmail",
            tls:{
                rejectUnauthorized: false
            },
            auth: {
                user: "...",
                pass: "..."
            }
        });

        var mail = {
            from: "...",
            to: "...",
            subject: "Send Email Using Node.js",
            text: "Node.js New world for me",
            html: fieldHeader
        }

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

            smtpTransport.close();
        });
    }
}
module.exports.init = init;

As I said, I print out the variable that contains the text I want to send in the mail (it's the console.log() you see at the beggining of the mailSender.js) and this is the result:

enter image description here

But the received mail, does not contain any line break: enter image description here

I have been thinking about replacing the line breaks with <br> using a loop that would look and check each character in the text, but I am not sure if it is a good idea.


Solution

  • Try adding break tags where you want line breaks. <br> or <br />

    var fieldheader = `hi <br> how are you ? <br> this is testing <br>`
    var mail = {
        from: "...",
        to: "...",
        subject: "Send Email Using Node.js",
        text: "Node.js New world for me",
        html: fieldHeader
    }
    

    It will solve your problem.