How to enable error In Nodemailer if email is not exist - node.js

nodemailer : "^2.4.2"
I am sending mail using nodemailer. It's working fine. But while using not existing email, I am not getting any error:
I have code as;
exports.sendMail = function (req, resp, reqBody, callback) {
var smtpTransport = nodemailer.createTransport(settings.smtpConfig);
var data = JSON.parse(reqBody);
var mailOptions={
to : data.toAddress,
cc : data.ccAddress,
bcc : data.bccAddress,
subject : data.subject,
html : data.message
}
smtpTransport.sendMail(mailOptions, function(error, response){
if (error) {
callback(null, error);
}else{
callback(response);
}
});
};
So if i use any not existing email Id it doesn't throw any error;
For eg:If I send toAddress as 'dummy#gmail.com' -- it doesn't throw any error.
I got response as
{ accepted: [ 'dummy#gmail.com' ],
rejected: [],
response: '250 2.0.0 OK 1466501212 23sm18003603qty.40 - gsmtp',
envelope: { from: '', to: [ 'dummy#gmail.com' ] },
messageId: '1466501201867-84b63b27-ce337819-b06c739f#localhost' }
Same case for cc also.
Any help appreciated.

Related

How to dynamically set aws ses TemplateData using node.js?

I'm trying to send an email with custom data.
async function sendEmailToSalesTeamOnBookingDemoClass(email,name,phoneNumber,utmSource,utmTerm,utmMedium,deviceType,browser,referrer) {
try {
let emailMe = "abc#gmail.com"
const ses = new AWS.SES({ apiVersion: "2010-12-01" });
const params = {
Destination: {
ToAddresses: [emailMe]
},
Source: senderEmail,
Template: "Sales_Email_Demo",
TemplateData : JSON.stringify({
"name": name,
"email": email,
"phone": phoneNumber,
"utmSource":utmSource,
"utmTerm":utmTerm,
"utmMedium":utmMedium,
"browser":browser,
"referrer":referrer,
"deviceType":deviceType
}),
Tags: [
{
Name: 'SomeName',
Value: 'info'
}
]
};
const sendEmailReceiver = ses.sendTemplatedEmail(params).promise();
sendEmailReceiver
.then(data => {
console.log(senderEmail,emailMe)
console.log("Email submitted to SES", data);
})
.catch(error => {
console.log("Email not submitted to SES:" + error);
});
}
catch (e) {
console.error(`Error: ${e}`);
}
}
The response says that the email was sent successfully.
Email submitted to SES {
ResponseMetadata: { RequestId: 'c08b9948-7be3-465d-a72c-fcca23f9f059' },
MessageId: '010901793bd95a02-813072dc-bb87-4b65-91c4-03f7f29dcbd0-000000'
}
But there is no email received even though the sender email has been verified and tested. Is there something wrong with my template?
{
"Template": {
"TemplateName": "Sales_Email_Demo",
"SubjectPart": "some subject!",
"HtmlPart": "<html> <body><p>Hello,</p><p>Details:</p><p>Name:{{name}}</p><p>Phone Number: {{phoneNumber}}</p><p>Email Id: {{emailId}}</p><p>Source: {{utmSource}}</p><p>Medium: {{utmMedium}}</p><p>Term:{{utmTerm}}</p><p>Device:{{deviceType}}</p><p>Browser:{{browser}}</p><p>Referrer: {{referrer}}</p></body></html>"
}
}
I figured it out. The issue was with the template. The sending and receiving variables were named differently.

gmail api auth issue - cannot get attachment from the chosen email

I'm working with node.js v13 with Gmail api.
I have done successfully getting the specific email message and now I'm trying
to get the attachment from that same email.
function getRecentEmail(auth) {
// Only get the recent email - 'maxResults' parameter
gmail.users.messages.list({ auth: auth, userId: 'me', maxResults: 1, q: 'subject:pokerrrr' }, function (
err,
response
) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// Get the message id which we will need to retreive tha actual message next.
const message_id = response['data']['messages'][0]['id'];
// Retreive the actual message using the message id
gmail.users.messages.get({ auth: auth, userId: 'me', id: message_id }, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// const attachment_id = response['data'].payload.parts[1].body.attachmentId;
const message = response['data'];
// getAttachments('me', message, auth);
const parts = message.payload.parts;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.filename && part.filename.length > 0) {
const attachId = part.body.attachmentId;
gmail.users.messages.attachments.get(
{
id: attachId,
messageId: message.id,
userId: 'me',
},
function (attachment) {
// saveAttachmentsToDir(part.filename, part.mimeType, attachment);
}
);
}
}
});
});
}
when I run the code above, the attachment parameter is showing me auth error and I cant understand why.
here is the error:
code:401
config:Object {url: "https://www.googleapis.com/gmail/v1/users/me/messa…", method: "GET", paramsSerializer: , …}
errors:Array(1) [Object]
message:"Login Required"
response:Object {config: Object, data: Object, headers: Object, …}
stack:"Error: Login Required
at Gaxios.<anonymous> (c:\Users\tomer\Desktop\Mail listener -tomer\Mail listener\node_modules\gaxios\build\src\gaxios.js:73:27)
at Generator.next (<anonymous>)
at fulfilled (c:\Users\tomer\Desktop\Mail listener -tomer\Mail listener\node_modules\gaxios\build\src\gaxios.js:16:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)"
__proto__:Error {constructor: }

Firebase cloud function http sending push notification to device successfully but it falls into the catch block with empty error

Firebase cloud function HTTP send a push notification to device,
notification is sending successfully but it falls into the catch
block with an empty error instead of response block
here's my index.js code:
exports.test = functions.https.onRequest((request, response) => {
var missingData = [];
var tokenPass = request.query.token_passed ? request.query.token_passed : missingData.push({
key : 'token',
message : "Token cannot be null"
});
if (missingData.length > 0) {
response.status(403);
responseData = {
status : 403,
success : false,
message : "Missing data input",
data : missingData
}
response.send(responseData);
return;
}
const payload = {
notification: {
title: 'Hi',
body: 'Body'
}
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().sendToDevice(tokenPass, payload)
.then((response) => {
response.status(200);
response.send({
status : 200,
success : true,
message : "send notification successful"
});
return;
})
.catch((error) => {
response.status(500);
response.send({
status : 500,
success : false,
err: error,
message : "internal error"
});
return;
});
});
Here's the response which I get:
{
"status": 500,
"success": false,
"err": {},
"message": "internal error"
}
I tried doing like this too, but no success:
var message = {
notification: {
title: titlePass,
body: bodyPass
},
token: tokenPass
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
P.S. I added the stripe module to my firebase functions, could it be causing issues?

Why can't I send emails through amazon ses on Node?

I'm using "aws-sdk": "^2.117.0", my code looks like this:
var AWS = require('aws-sdk');
exports.sendAWSMail = function(message, destination){
const ses = new AWS.SES();
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property
const sendEmail = ses.sendEmail;
var data = {
Destination: {
ToAddresses: [
"blahblah#gmail.com"
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>."
},
Text: {
Charset: "UTF-8",
Data: "This is the message body in text format."
}
},
Subject: {
Charset: "UTF-8",
Data: "Test email"
}
},
Source: "no-reply#frutacor.com.br",
}
sendEmail(data)
}
But I get this error:
TypeError: this.makeRequest is not a function
at svc.(anonymous function) (/Users/iagowp/Desktop/trampos/frutacor/node_modules/aws-sdk/lib/service.js:499:23)
I didn't find any Node examples at their website, but from what I've seen elsewhere (like here), it looks correct. What am I doing wrong?
The main problem is in line #5 and it's always a good idea to add the callback function for logging errors and successful requests.
var AWS = require('aws-sdk');
exports.sendAWSMail = function(message, destination){
const ses = new AWS.SES();
var data = {
Destination: {
ToAddresses: [
"blahblah#gmail.com"
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>."
},
Text: {
Charset: "UTF-8",
Data: "This is the message body in text format."
}
},
Subject: {
Charset: "UTF-8",
Data: "Test email"
}
},
Source: "no-reply#frutacor.com.br",
}
ses.sendEmail(data, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}

sendgrid : add cc in email

I am sending email using sendgrid from my app. Now I want to add cc or bcc if user reply to my mail. How Do I do this. let me explain first. I am sending answer of user's feedback comes on my web application using my application let say I am sending email via 'noreply#mydomain.com', and user receive this mail in his/her inbox in gmail/yahoo or any other email service. In this case user may click reply to this mail. so now, yours 'To:' has contain 'noreply#mydomain.com' default reply address. it's fine. Now I want to add 'cc:' (carbon copy) as follows 'feedback#mydomain.com'. How to do this?
You can pass the cc value when calling the sendgrid npm module. See below.
var sendgrid = require('sendgrid')(api_user, api_key);
var email = new sendgrid.Email({
to: 'foo#bar.com',
from: 'you#yourself.com',
cc: 'someone#else.com',
subject: 'Subject goes here',
text: 'Hello world'
});
sendgrid.send(email, function(err, json) {
if (err) { return console.error(err); }
console.log(json);
});
For sendGrid V3 you can follow this process to add .
var sgMailHelper = require('sendgrid').mail,
sg = require('sendgrid')('apiKey');
var sender = new sgMailHelper.Email(sender, senderName||'');
var receiver = new sgMailHelper.Email(receiver);
var content = new sgMailHelper.Content("text/plain", "Test mail");
var subject = "Mail subject";
var mailObj = new sgMailHelper.Mail(sender, subject, receiver, content);
// add cc email
mailObj.personalizations[0].addCc(new sgMailHelper.Email('cc.email#gmail.com'));
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mailObj.toJSON()
});
sg.API(request, function(error, response) {
if(error) {
console.log(error)
} else {
console.log('success')
}
});
If you are using version 7.6.2 of #sendgrid/mail, there is a cc attribute that works:
import sgMail from '#sendgrid/mail'
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
const msg = {
to: toAddress,
from: fromAddress, // Use the email address or domain you verified above
cc: ccAddress,
subject: `Fresh message from - ${name}`,
text: `A new message was sent by ${name} from ${ccAddress}.
${message}
`,
html: `
<p>hello world</p>
<blockquote>${message}</blockquote>
`,
}
//ES8
try {
await sgMail.send(msg)
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: 'contactSubmission function',
}),
}
} catch (error) {
console.error(error)
if (error.response) {
console.error(error.response.body)
}
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'error in email submission',
}),
}
}

Resources