Keep getting Bounce message when using Gmail API - node.js

I try to use gmail API to send emails form node application. Here is my code:
function sendEmail(auth) {
var gmail = google.gmail('v1');
gmail.users.messages.send({
auth,
userId: 'me',
resource: {
payload: {
mimeType: 'message/rfc822',
headers: [{name: 'To', value: 'ayeritsian#gmail.com'},
{name: 'Subject', value: 'test'},
{name: 'From', value: 'ayeressian2#gmail.com'}]
},
raw: new Buffer('test123').toString('base64')
},
internalDate: Date.now()
}, function (err, bla, IncommingMessage) {
console.log(arguments);
console.log('end');
});
}
When I run the application I keep getting bounce messages "An error occurred. Your message was not sent.". The error message is not descriptive enough and there is almost no documentation for google-api node package. I will appreciate it if someone can help me out.

You need to put the entire email in the "raw" field on the message, the parsed-out message doesn't work with send. c.f. https://developers.google.com/gmail/api/guides/sending
this is something akin to python, i'm sure you can translate to node.js :)
email = "From: myemail#gmail.com\r\nTo: someguy#gmail.com\r\nSubject: hey check this out\r\n\r\nhi someguy, this is my email body here. it's plain text."
message.raw = base64_websafe(email)

For what it's worth I had a similar issue to yours. I kept getting a vague error message in the inbox of my app/user.
From: nobody#gmail.com
An error occurred. Your message was not sent.
What resolved the issue for me was adding the Message-ID property to the Buffer I created. Basically, my message wasn't composed to the rfc822 spec that they mention in the docs here. 😁
Here is the document I referenced and below is my snippet.
module.exports = function (policyMeta) {
log.info('BUILDING EMAIL');
const message = 'From: xxx#xxx.com\r\n' +
'To: xxx#xxx.com\r\n' +
`Date: ${new Date()}\r\n` +
'Subject: Howdy Mundo\r\n' +
`Message-ID: ${uuid()}\r\n` +
'look mom i send a message';
const params = {
auth: Auth.getGoogleAuthClient(),
userId: 'me',
media: { mimeType: 'message/rfc822' },
resource: {
raw: new Buffer(message).toString('base64')
}
};
return sendEmail(params).then((res) => console.log(res, '🔥🔥success🔥🔥'));
};

Related

GCP Cloud Function for Slash command not working

so i'm trying to make an slash command on my slack using nodejs and Cloud Functions. I'm getting error 403 when the slash command goes out to the function, but i'm having problems to identify why it's giving me the error.
The code of the function is this:
const { WebClient } = require('#slack/web-api');
exports.slashCommand = (req, res) => {
// Verify that the request is coming from Slack
if (!req.body.token || req.body.token !== process.env.SLACK_TOKEN) {
res.status(403).end();
return;
}
// Parse the request body and extract the Slack user ID, command text, and response URL
const { user_id, text, response_url } = req.body;
// Use the Slack Web API client to post a message to the response URL
const web = new WebClient();
web.chat.postMessage({
channel: user_id,
blocks: [
{
type: 'section',
text: {
type: 'plain_text',
text: 'This is a section block'
}
},
{
type: 'divider'
},
{
type: 'section',
fields: [
{
type: 'plain_text',
text: 'This is a field'
},
{
type: 'plain_text',
text: 'This is another field'
}
]
}
]
});
// Send a 200 OK response to acknowledge receipt of the request
res.status(200).end();
};
I'm using nodeJS 18 to build
I also created gen 1 and gen2 with the same code, but the problem persists. I've given permission to allUsers to call the URL, but still no go. My SLACK_TOKEN is configured in the env. I'm suspecting that's something in the payload but i'm not understanding why this is happening. ( i'm new to this, so i'm sorry for the lack of details, if theres something i should add, let me know ).
Tried to give permission to allUsers, and still getting error. I'm really struggling to make slack validate the payload so my guess is the code checking if the payload and the token is valid is breaking everything.

Amazon Pinpoint SMS For India

I am trying to implement Amazon's Pinpoint SMS. There is a special requirement for India to send SMS. I have followed this Documentation and added EntityId and TemplateId as extra parameters to pinpoint.sendMessages. But when I do, I am getting.
UnexpectedParameter: Unexpected key 'EntityId' found in params.MessageRequest.MessageConfiguration.SMSMessage
UnexpectedParameter: Unexpected key 'TemplateId' found in params.MessageRequest.MessageConfiguration.SMSMessage
Code
Refrence: AWS Official Pinpoint SMS Doc
let params = {
ApplicationId: applicationId,
MessageRequest: {
Addresses: {
[destinationNumber]: {
ChannelType: 'SMS'
}
},
MessageConfiguration: {
SMSMessage: {
Body: body,
EntityId: entityID,
Keyword: registeredKeyword,
MessageType: messageType,
OriginationNumber: originationNumber,
SenderId: senderId,
TemplateId: templateID
},
}
}
};
//Try to send the message.
pinpoint.sendMessages(params, function (err, data) {
// If something goes wrong, print an error message.
if (err) {
console.log(err.message);
// Otherwise, show the unique ID for the message.
} else {
console.log(data)
// console.log("Message sent! "
// + data['MessageResponse']['Result'][destinationNumber]['StatusMessage']);
}
});
Migrating AWS-SDK from 2.467.0 to 2.850 solved my issue.

Node JS - nodemailer & imap-simple - Identify threads

(I feel sorry for my poor english, but i'll do my best !) :)
I'm trying to setup a local mailbox for a personnal project, and i'm trying to use imap-simple and nodemailer to do that.
I want to be able to identify a thread, when i send an e-mail.
Here's what i exactly want to do :
In my application, i'll be able to send an e-mail to a specific person (let's admit foo#bar.com)
When the mail is sent, a callback function will store mail content and subject in DB (for example, in a CRM app, i will store the sent mail which will be related to a specific record in my database).
The complex part is just after that :
When the person replies to this e-mail, i want using IMAP to identify that this person is answering to my previous mail, and then store it in DB too, also linked to the same record i used on my first e-mail.
I actually have this in a sandbox folder (For IMAP) :
var imaps = require('imap-simple');
var nodemailer = require('nodemailer');
var config = {
imap: {
user: 'catchall#xxxxxxxx.fr',
password: 'xxxxxxxx',
host: 'imap.gmail.com',
port: 993,
tls: true,
authTimeout: 3000
}
};
imaps.connect(config).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = [
'UNSEEN'
];
var fetchOptions = {
bodies: ['HEADER', 'TEXT'],
markSeen: false,
};
console.log('Passing there');
return connection.search(searchCriteria, fetchOptions).then(function (results) {
var subjects = results.map(function (res) {
return res.parts.filter(function (part) {
return part.which === 'HEADER';
})[0].body.subject[0];
});
console.log('BASE');
console.log(results[0]);
console.log('FIRST');
console.log(results[0].parts[0]);
console.log('SECOND');
console.log(results[0].parts[1]);
});
});
});
And here is the SMTP part :
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'catchall#xxxxxxxx.fr',
pass: 'xxxxxxxx'
}
});
const mailOptions = {
from: 'catchall#xxxxxxxx.fr', // sender address
to: 'xxxxxxxx#gmail.com', // list of receivers
subject: 'Subject of your email', // Subject line
html: '<p>Here is my test !</p>',// plain text body
headers: {
'collection': 'Pipelines',
'doc-ID': 'mydocid'
}
};
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else
console.log(info);
});
Here is a screen of what i want to be able to :
On IMAP, i'm getting exactly the information i want in console :
BASE
{ attributes:
{ date: 2019-12-05T16:53:07.000Z,
flags: [],
uid: 94,
modseq: '27800',
'x-gm-labels': [ '\\Important' ],
'x-gm-msgid': '1652099423356172171',
'x-gm-thrid': '1652099362185438260' },
x-gm-thrid allow me to identify a thread. Perhaps, i can't find this information in the nodemailer callback function :
Server is ready to take our messages
{ accepted: [ 'xxxxxxxxxxxxxxxxx#gmail.com' ],
rejected: [],
envelopeTime: 400,
messageTime: 819,
messageSize: 346,
response: '250 2.0.0 OK 1575566223 m3sm12955793wrs.53 - gsmtp',
envelope:
{ from: 'catchall#xxxxxxxxxx.fr',
to: [ 'xxxxxxxxxxxx#gmail.com' ] },
messageId: '<f93b3970-e17a-84b5-d0d1-ebb4fd6efe46#xxxxxxxxxx.fr>' }
Does anyone have an idea of how i could proceed ?
Thanks a lot btw !
Happy coding :)
For those who will read this post, here the answer, thanks to #arnt,
As #arnt said, there is for IMAP protocol, a reference attribute which is storing the previous message ID stored in results[0].parts[1] :
references: [ '<23df0af1-8ff1-0ffa-091e-a645a38e4a67#foobar.fr>' ],
'in-reply-to': [ '<23df0af1-8ff1-0ffa-091e-a645a38e4a67#foobar.fr>' ],
This one is also available when you send a message, in info :
envelope:
{ from: 'foobar#foobar.fr',
to: [ 'foobar#gmail.com' ] },
messageId: '<23df0af1-8ff1-0ffa-091e-a645a38e4a67#foobar.fr>' }
This way, we're able to correlate mail conversation.
Thanks a lot for help :)
Topic closed

AWS SES Error: Email address is not verified

I am trying to send email using aws-sdk ses in nodejs.
While executing the code the response I am getting is:
message:
'Email address is not verified. The following identities failed the check in region US-EAST-1:xxxtestemailxxx#gmail.com',
code: 'MessageRejected'
I have already verified the sender as well as receiver email(destination email in a array).
On SES settings of aws console, it is showing the email is verified. I removed the email and then once again successfully verified it.
Last time(few months back) when I used it, everything was working fine.
Below is the screenshot of my aws console related to SES:
Also when I am sending the test email using aws console, its working fine. This is only happening when I am trying to send email using aws-sdk.
Does anyone knows what is wrong, just to be clear I am also posting the code below:
const send_email = function (email, subject, source, payload) {
console.log(email, subject, source, payload);
let email_param = {
Destination: {
ToAddresses: email
},
// ConfigurationSetName: 'XXXRANDOMTEXT_PLATFORM',
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: payload
}
// Text: {
// Charset: "UTF-8",
// Data: payload
// }
},
Subject: {
Charset: "UTF-8",
Data: subject
}
},
Source: source
};
let send_email = SES.sendEmail(email_param).promise();
send_email
.then(data => {
return true;
})
.catch(error => {
console.log('sending email error:', error);
return false
});
}
If your AWS account is still in the sandbox mode then you have to verify your sender, receiver etc. Go to the prod mod to have access to the full features.

braintree + NodeJS gives an "authentication Error "

I'm trying to build a payment gateway library using braintree's NodeJS library, I'm making an ajax call from front end with the card data.
Client-Side
var card_data = {
type: "AmEx",
number: "3XXXXXXXXXXXXXX",
expire_month: "XX",
expire_year: "201X",
cvv2: "XXX",
name: "sandeep",
price : "200",
currency : "USD"
};
Ajax call,
$.ajax({
method: "GET",
url: "http://localhost:3000/paymentPath_braintree",
data: card_data
}).done(function(message){
console.log(message);
}).fail(function(data, message){
console.log(message);
});
Server-Side
var braintreePay = require('braintree');
app.get("/payment_braintree", function(request, response){
var data = request.query;
var gateway = braintreePay.connect({
environment: braintreePay.Environment.Sandbox,
merchantId: "MymerchentID",
publicKey: "MypublicKey",
privateKey: "MyprivateKey",
});
var saleRequest = {
amount: data.price,
creditCard: {
number: data.number,
cvv: data.cvv2,
expirationMonth: data.expire_month,
expirationYear: data.expire_year.slice(2),
cardHolder: data.name
},
options: {
submitForSettlement: true
}
};
gateway.transaction.sale(saleRequest, function(error, result){
if(error){
console.log(error.name);
throw error;
}
if(result.success){
response.send(result.transaction.id);
} else {
response.send(result.message);
}
});
});
I have cross checked everything, from keys and card data everything is in order but i am getting an error in callback after making gateway.transaction.sale(...); called Authentication Error . Which i tried to figure out for hours but could not get through.
error object is
authenticationError: Authentication Error
arguments: undefined
message: "Authentication Error"
name: "authenticationError"
stack: undefined
type: "authenticationError"
Where am i going wrong?
I have created an account sandbox.braintreegateway those key credentials are from the account that i have created, i din't create an app like how its done in paypal.
I am going through lack of understanding in Braintree integration.
Are their any proper documented resource.

Resources