NodeJS params.Example not being used by #sendgrid/mail - node.js

Watson Assistant passes my params.finalemail and params.guestemail correctly. It looks like your #sendgrid/mail is not accepting the values of these params. Why is that?
Basically, Watson passes the $guest email as the "to" email address and the $finalemail contain the main body of the email.
I need my function to send an email with the information contained in the above varibles.
const sgMail = require('#sendgrid/mail');
/* Replace YOUR-SENDGRID-API-KEY-GOES-HERE with
the API Key you get from SendGrid.
*/
sgMail.setApiKey('apikey')
function sendmail(params) {
params.guestemail
params.finalemail
let msg = {}
msg.to = params.guestemail
msg.from = 'example#outlook.com'
msg.subject = 'Your Reservation'
msg.html = params.finalemail
sgMail.send(msg,(error, json) => {
if (error) {
console.log(error)
}
})
return { sent: 1 }
}

Sendgrid will send either text field or html not both. To send the message that you want you can add 'This message is HTML only.' in an html tag.

Related

how to send a mail in a particular format by using send grid

I am able to send a mail by using send grid API how to send a mail in particular format by using send grid
Mail-Format
please find the Mail-format image
Pass in the body as HTML and set the IsBodyHtml = true. I do this using SendGrid.
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var client = new SmtpClient(host, port)
{
Credentials = new NetworkCredential(userName, password),
EnableSsl = false
};
return client.SendMailAsync(
new MailMessage(from, email, subject, htmlMessage) { IsBodyHtml = true }
);
}

How to get email of user who send message to bot in Circuit JavaScript SDK?

I'm creating a bot that will receive a messages in Circuit and then send it somewhere else with email of user that printed this message.
As example I use xlator-bot https://github.com/circuit/xlator-bot
this.receiveItem = function receiveItem(item) {
logger.info('[APP]: receiveItem');
if (item.type !== 'TEXT' || self.sentByMe(item)) {
logger.debug('[APP]: skip it is not text or I sent it');
return;
}
if (!item.text || !item.text.content) {
logger.info('[APP]: skip it does not have text');
return;
}
self.receiveText(htmlToText.fromString(item.text.content))
.then (function addResponseItem(responseItem){
logger.info('[APP]: addResponseItem');
var comment = {
convId: item.convId,
parentId: (item.parentItemId) ? item.parentItemId : item.itemId,
content: responseItem
};
return client.addTextItem(item.convId, comment);
})
.catch(function(e){
logger.error('[APP]:', e);
});
};
I want to get email of user who send item in this function as string variable. Can anyone suggest how can I do it?
The item has an attribute creatorId which is the userId of the sender. The API getUserById will return the user object that contains the emailAddress attribute.
See
https://circuitsandbox.net/sdk/classes/Item.html#property_creatorId and https://circuitsandbox.net/sdk/classes/Client.html#method_getUserById and
https://circuitsandbox.net/sdk/classes/User.html#property_emailAddress

Cloud Function for Firebase: Email Duplicates

Im trying to implement some code that sends an email to anyone who would like to sign up to my newsletter. The code is actually working, but it sends multiple duplicates. Im using Firebase' samplecode, like this.
I think the problem is that it listensens for every change on the {uid} and I'm setting 4 values. If I manually change anything at the database from the dashboard, it triggers the event and sends a new mail. My code:
'use strict';
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
`smtps://${gmailEmail}:${gmailPassword}#smtp.gmail.com`);
// Sends an email confirmation when a user changes his mailing list subscription.
exports.sendEmailConfirmation = functions.database.ref('/mailingList/{uid}').onWrite(event => {
const snapshot = event.data;
const val = snapshot.val();
if (!snapshot.changed('subscribed')) {
return;
}
const mailOptions = {
from: '"Spammy Corp." <noreply#firebase.com>',
to: val.email
};
// The user just subscribed to our newsletter.
if (val.subscribed == true) {
mailOptions.subject = 'Thanks and Welcome!';
mailOptions.text = 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.';
return mailTransport.sendMail(mailOptions).then(() => {
console.log('New subscription confirmation email sent to:', val.email);
});
}
});
A database trigger will run for each change made to the path it's monitoring, and you need to plan for that. In your function, you need a way to figure out if the email has already been sent. The typical solution is to write a boolean or some other flag value back into the node that triggered the change, then check for that value every time and return early if it's set.

Retrieving fields of email with logic apps / azure function

I have a use case where an HTML form is filled with user data and an email is sent to their email address, CC'ed to a logic app.
The logic app would receive this email and read only the values after name: and email form fields so that I can pass them along to another function.
How would one do this in a logic apps or within an Azure function?
This blog has great information on using Azure Functions from Logic Apps.
Assuming you have the logic app set up to receive emails, you then add a step to process emails in an Azure Function App sending the email content as an input.
Sample Input payload to nodejs webhook trigger:
{
"email": {
"emailBody": "Body×​​",
"text": "Hello from Logic Apps"
}
}
Note: "Bodyx" is the dynamic content representing the email body that was received in an earlier step.
Corresponding index.js in the function app:
module.exports = function (context, data) {
var email = data.email;
// You can now do processing on the emailBody
context.log('email body', email.emailBody);
context.res = {
body: {
greeting: 'Hello !' + email.text
}
};
context.done();
};
Hope this helps!

I'm trying to send emails using sendgrid in nodejs.But am getting "TypeError: object is not a function" error

Here is my code snippet
var sendgrid = require('sendgrid')('xxxxxx', 'xxxxxx');
var email = new sendgrid.Email();
email.addTo('xyz#gmail.com');
email.setFrom('xyz#gmail.com');
email.setSubject('welcome to send grid');
email.setHtml('<html><body>HELLO evryone ...,</body></html>');
sendgrid.send(email, function(err, json) {
if(!err)
{
console.log("mail sent successssss");
res.send({"status":0,"msg":"failure","result":"Mail sent successfully"});
}
else
{
console.log("error while sending mail")
res.send({"status":1,"msg":"failure","result":"Error while sending mail."});
}
});
Installed sendgrid throgh npm also.am getting "TypeError: object is not a function" error.MAy i know why.??
Version:--
sendgrid#3.0.8 node_modules\sendgrid
└── sendgrid-rest#2.2.1
It looks like you're using sendgrid#3.0.8 but trying to call on the sendgrid#2.* api.
v2 implementation: https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/nodejs.html
v3 implementation:
https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/nodejs.html
Give the v3 a go.
As for the type error:
v2
var sendgrid = require("sendgrid")("SENDGRID_APIKEY");
you're invoking a function
however you have v3 installed
require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
and it's now an object
REQUESTED UPDATE:
I don't know too much about the keys given, but since they have tons of different supported libraries, it's completely possible that some of them use both while others use only one. If you really only have a USER_API_KEY nad PASSWORD_API_KEY, just use the user_api_key
Here is their source for the nodejs implementation module SendGrid:
function SendGrid (apiKey, host, globalHeaders) {
var Client = require('sendgrid-rest').Client
var globalRequest = JSON.parse(JSON.stringify(require('sendgrid-rest').emptyRequest));
globalRequest.host = host || "api.sendgrid.com";
globalRequest.headers['Authorization'] = 'Bearer '.concat(apiKey)
globalRequest.headers['User-Agent'] = 'sendgrid/' + package_json.version + ';nodejs'
globalRequest.headers['Accept'] = 'application/json'
if (globalHeaders) {
for (var obj in globalHeaders) {
for (var key in globalHeaders[obj] ) {
globalRequest.headers[key] = globalHeaders[obj][key]
}
}
}
The apiKey is attached to the header as an auth, and it looks like that's all you need.
Try following their install steps, without your own implementation,
1) (OPTIONAL) Update the development environment with your SENDGRID_API_KEY, for example:
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
========
2) Make this class and if you did the above use process.env.SENDGRID_API_KEY else put your USER_API_KEY
var helper = require('sendgrid').mail
from_email = new helper.Email("test#example.com")
to_email = new helper.Email("test#example.com")
subject = "Hello World from the SendGrid Node.js Library!"
content = new helper.Content("text/plain", "Hello, Email!")
mail = new helper.Mail(from_email, subject, to_email, content)
//process.env.SENDGRID_API_KEY if above is done
//else just use USER_API_KEY as is
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
var requestBody = mail.toJSON()
var request = sg.emptyRequest()
request.method = 'POST'
request.path = '/v3/mail/send'
request.body = requestBody
sg.API(request, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})

Resources