How to send base64 string as image in Node.js using nodemailer? - node.js

I have nodejs get request which need to send the base 64 string as image in the email which as shown below
router.post('/sendEmailNotification', function(req, res, next){
var inlineBase64 = require('nodemailer-plugin-inline-base64');
//here i have big image
let img ='/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBx'
var transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 587,
secure: false,
// secure: true,
secureConnection: false,// true for 465, false for other ports
auth: {
user: 'dhanalakshmi.07k#gmail.com',
pass: '23'
},
tls:{
rejectUnauthorized:false
}
});
transporter.use('compile', inlineBase64({cidPrefix: 'somePrefix_'}));
var mailOptions = {
from: 'dhanalakshmi.06k#gmail.com',
to: 'dhanalakshmi.06k#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!',
html: '<img src=data:image/png;base64,'+img+'/>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
res.send(info.response);
}
});
});
after the email send this should received as image but it showing the entire tag with image string please say
html: '<img src=data:image/png;base64,'+img+'/>' how should i send this to get the actual image

Use it like this:
html: '<html><body><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA9QAAADmCAIAAAC77FroAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAO..."></body></html>'

Related

Sending Email using nodemailer

I am trying to send emails to using nodemailer from my site but it gives me this error
Error: Invalid login: 535-5.7.8 Username and Password not accepted.
and I made sure the password and credentials is accurate. This is my code for setting up nodemailer
function message(merchantEmail, msgTxt){
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
secure: true,
port: 465,
auth: {
user: 'kesterdaniel401#gmail.com',
pass: process.env.PASSWORD
},
tls: {
rejectUnauthorized: false
}
});
var mailOptions = {
from: 'kesterdaniel401#gmail.com',
to: merchantEmail,
subject: 'Sending Email using Node.js',
text: msgTxt
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
module.exports = message
This is where I called the function
message(productOwner.Email, `You have received an order from ${Buyer.Name} for the product ${product. ProductName}. Please contact the customer as soon as possible. Customer Number is ${Buyer.PhoneNumber}.`)

Nodemailer - Missing credentials for "PLAIN"

I am working with node.js and tried sending email via Nodemailer but I'm getting this error:
Missing credentials for "PLAIN"
function(token, user, done) { //sends mail
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'aimanmumtazxyz#gmail.com',
pass: process.env.GMAILPW
}
});
Any help anybody?
const nodemailer = require("nodemailer");
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: userName, // Enter your userName or email
pass: password // Enter your password
}
});
// send mail with defined transport object
await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: "bar#example.com, baz#example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>" // html body
}, (err, info)=>{
if (err) {
throw new Error(err)
} else {
console.log('Email sent: ' + info.response);
}
});
For more information about nodemailer, please check this link: https://nodemailer.com/about/
For sending an email by Gmail, please check this link: https://nodemailer.com/usage/using-gmail/

Nodemailer ECONNREFUSED

I am trying to use nodemailer to send an email but I keep getting this error:
Here is my code:
const nodemailer = require('nodemailer');
...
app.post('/api/SendEmail', (req, res) => {
var transporter = nodemailer.createTransport({
auth: {
user: 'x#gmail.com',
pass: 'x'
}
});
var mailOptions = {
from: 'x#gmail.com',
to: 'x#incasu.co.za',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(err, info) {
if (err) return res.status(400).send(err);
return res.status(200).send({response: 'success'});
});
})
Could someone please help me with this. I basically followed this process: https://www.w3schools.com/nodejs/nodejs_email.asp
UPDATE:
I added service: 'gmail', in the transporter as suggested by Janith Kasun:
service: 'gmail',
auth: {
user: 'x#gmail.com',
pass: 'x'
}
My error now changed to this:
I found this answer:
NodeJs Error When Submitting Email using Nodemailer
I have no idea what any of these settings do, but my emails are now being sent correctly with this code:
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: '587',
auth: {
user: "**",
pass: "**"
},
secureConnection: 'false',
tls: {
ciphers: 'SSLv3',
rejectUnauthorized: false
}
});

sending mail with nodemailer

whenever i run the code I'm getting the error " Error: Greeting never received at SMTPConnection._formatError...."
function automatedMailSender(req,res){
var mailOptions = {
from: "abc <abc#test.com>", // sender address
to: 'nit#test.com', // list of receivers
subject: 'Hello ', // Subject line
text: 'Hello world ?', // plain text body
html: '<b>Hello world ?</b>' // html body
};
var mailer=nodemailer.createTransport({
host: 'mail.test.com',
port: 465,
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'mymail#test.com',
pass: '1234'
}
});
mailer.sendMail(mailOptions, (error, response)=>{
if(error){
console.log('mail not sent \n',error);
}
else{
console.log("Message sent: " ,response.message);
}
});
}
I'm I doing something wrong in the code.
The answer in right in your code
port: 465,
secure: false, // secure:true for port 465, secure:false for port 587
The value for "secure" should be true for port 465
If you are using Gmail to send mails then try this.
Allow less secure apps to connect to Gmail.
Try something like that, it work perfectly for me:
//Create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(
'smtps://USERNAME%40gmail.com:PASSWORD#smtp.gmail.com');
// setup e-mail data
var mailOptions = {
from: '"Michel 👥" <recipe#example.com>', // sender address
to: 'bernard#example.com', // list of receivers
subject: 'Hello', // Subject line
text: 'Bonjour!' // plaintext body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
If is still doesn't work you have a little tuto here
var mailer=nodemailer.createTransport({
host: 'mail.test.com',
port: 465,
secure: true, // secure:true for port 465, secure:false for port 587
transportMethod: 'SMTP',
auth: {
user: 'mymail#test.com',
pass: '1234'
}
});
The value for secure should be true for port 465 and use transportMethod: 'SMTP'
const express = require('express');
const router = express.Router();
const { Email } = require('../models/email.model');
const { User } = require('../models/user.model');
const nodemailer = require('nodemailer');
//post email
router.post('/send', async (req, res) => {
if (req.query) {
var query = {}
if (req.query.lastname) { query.lastname = req.query.lastname }
if (req.query.firstname) { query.firstname = req.query.firstname }
if (req.query.email) { query.email = req.query.email }
if (req.query.isactive) { query.isActive = req.query.isactive }
if (req.query.isgain) { query.isGain = req.query.isgain }
}
const email = new Email({
title: req.body.title,
subject: req.body.subject,
text: req.body.context,
description: req.body.description
});
if (req.body.title && req.body.subject && req.body.context) {
const user_db = await User.find(query)
const user_db_email = user_db.map(x => x.email)
var smtpTransport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: { user: 'ghiles#gmail.com', pass: 'g' },
tls: { rejectUnauthorized: false }, // do not fail on invalid certs
});
var mailOptions = {
to: user_db_email,
from: 'fatb#gmail.com',
subject: req.body.subject,
text: req.body.context
};
email.save().then(() => {
smtpTransport.sendMail(mailOptions)
.then(() => res.status(200).json(email))
.catch(() => res.status(500).json({ success: false, message: `erreur dans l'envoi de mail` }))
}).catch(() => res.status(200).json({ success: false, message: `erreur dans le serveur` }))
} else {
res.status(400).json({ success: false, message: `Veuillez renseigner le titre et l'objet et le contexte du mail` })
}
module.exports = router;
tls:{
rejectUnauthorized:false
}
fixed it by using the above code in mailer variable.
Thanks guys
host: 'smtp.host.com',
port: 587, // 587 or 25 or 2525
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'mymail#test.com',
pass: '1234'
}
Try this. prefixing smtp and changing the port.

nodemailer attachment text file

I failed to attach a txt file that I created earlier in the script to a mail to be sent via nodemailer. The mail is successfully sent however, it is empty. How would I fix this?
var nodemailer = require ('nodemailer');
let transporter = nodemailer.createTransport({
service: 'gmail',
secure: false,
port: 460,
auth: {
user: 'name#gmail.com',
pass: 'password'
},
tls: {
rejectUnauthorized: false
}
});
let mailOptions = {
from: "name" <'name#gmail.com',
to: 'name#gmail.com',
subject: 'group_1',
attachement: [ {
filename: 'group_1.txt',
path: /Users/derinserbetcioglu/Documents/NodeJS/'group_1.txt' } ]
};
transporter.sendMail(mailOptions, (error, info) => {
if (error){
console.log(error);
}
console.log("the message was successfully sent!")
console.log(info);
})
Try the path as path:
'/Users/derinserbetcioglu/Documents/NodeJS/group_1.txt'
instead of path: /Users/derinserbetcioglu/Documents/NodeJS/'group_1.txt'
And i think it should be attachments not attachment

Resources