I'm trying to send an email using SendGrid with Azure Mobile Services. I'm using the sample code here for reference:
http://azure.microsoft.com/en-us/documentation/articles/store-sendgrid-nodejs-how-to-send-email/
exports.post = function(request, response) {
var SendGrid = require('sendgrid');
var toEmail = 'myemail#mydomain.com';
var mail = new SendGrid.Email({
to: toEmail,
from: toEmail,
subject: 'Hello SendGrid',
text: 'This is a sample email message.'
});
var sender = new SendGrid('my_user','my_ key');
};
I'm getting an TypeError creating the sender. The Email object is created as expected. I'm not sure what I'm doing wrong. From looking at the code in sendgrid.js, the exports look correct. Any ideas?
Here is the error:
Error in script '/api/my_api.js'. TypeError: object is not a function
Note:
I have added sendgrid using npm
From sendgrid.js
var Sendgrid = function(api_user, api_key, options) {
}
module.exports = Sendgrid;
Per the github docs:
var sendGrid = require('sendgrid')('my_user', 'my_key');
var mail = new sendGrid.Email({
to: toEmail,
from: toEmail,
subject: 'Hello SendGrid',
text: 'This is a sample email message.'
});
https://github.com/sendgrid/sendgrid-nodejs
sendgrid.Email is a method of the object returned by instantiating the module. To access sendgrid.Email, you must call the function returned by requiring SendGrid.
Your code should look as follows:
exports.post = function(request, response) {
var sendgrid = require('sendgrid');
var sender = new sendgrid('my_user','my_ key');
var toEmail = 'myemail#mydomain.com';
var mail = new sender.Email({
to: toEmail,
from: toEmail,
subject: 'Hello SendGrid',
text: 'This is a sample email message.'
});
};
Edit: Corrected method names.
The SendGrid package was not being imported correctly. I was thrown off the error because the Email object was being created correctly.
I rechecked my package.json and updated the project with npm install. Everything started working.
Some of the answers above helped me, but I still had to figure this out.
Here is what I did to fix the object is not a function error when using sendgrid. This is obviously, version specific, so you may have to adjust the version number depending on the version of sendgrid you are using.
Add sendgrid as a dependency in the package.json file of your azure mobile services project.
"dependencies": {
"sendgrid": "^1.9.2"
},
"devDependencies": {
"sendgrid": "^1.9.2"
},
The instructions at https://github.com/sendgrid/sendgrid-nodejs clearly state this, but somehow, I overlooked it.
Related
I'm using the botframework-connector npm package. And I want to use the sendOperationRequest & sendRequest methods from the ConnectorClient instance.
I have searched for the method examples here but can not find them.
Can anyone help me, please?
Edit:
I know how to use the create/update conversations via Conversations methods. I'm trying to scope whether I can use the package for other operations such as createChannel, add members to a group etc.
You should explore code samples in
https://github.com/microsoft/BotBuilder-Samples/tree/main/samples
rather than trying to understand how to use the SDK through the class references.
sendOperationRequest & sendRequest aren't really meant to be used explicitly, ConnectorClient uses it to send the request.
In order to send your message you first need a conversation reference (otherwise, how would the bot know which conversation to send the message to?) For example, look at the sample code on the documentation page of the NPM package you linked :
var { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
async function connectToSlack() {
var credentials = new MicrosoftAppCredentials('<your-app-id>', '<your-app-password>');
var botId = '<bot-id>';
var recipientId = '<user-id>';
var client = new ConnectorClient(credentials, { baseUri: 'https://slack.botframework.com' });
var conversationResponse = await client.conversations.createConversation({
bot: { id: botId },
members: [
{ id: recipientId }
],
isGroup: false
});
var activityResponse = await client.conversations.sendToConversation(conversationResponse.id, {
type: 'message',
from: { id: botId },
recipient: { id: recipientId },
text: 'This a message from Bot Connector Client (NodeJS)'
});
console.log('Sent reply with ActivityId:', activityResponse.id);
}
The botID and recipientID is dependent on the channel you use.
Edit : As I misunderstood the intent of the question.
If you want to create a channel, check out
https://github.com/howdyai/botkit/blob/main/packages/docs/core.md
There are officially supported channels with adapters that you can utilize. But if you are looking to connect to a custom app, look at https://github.com/howdyai/botkit/blob/main/packages/docs/reference/web.md#webadapter
for the generic web adapter that you can use to send and receive messages.
When sending an email using nlapiSendEmail() can I specify a email template to use?
I have created an email template in the NetSuite backend. Is there a function I can use to send an email and use that email template?
You can try using nlapiCreateEmailMerger(templateId) to get the body and subject of the email:
var emailMerger = nlapiCreateEmailMerger(templateId);
var mergeResult = emailMerger.merge();
var body = mergeResult.getBody();
var subject = mergeResult.getSubject();
nlapiSendEmail(author, recipient, subject, body, null, null, null, null);
I do mine like this:
var emailSendID='xxxx'; // Email author ID
var emailTempID=123; // Template ID
var emailTemp=nlapiLoadRecord('emailtemplate',emailTempID);
var emailSubj=emailTemp.getFieldValue('subject');
var emailBody=emailTemp.getFieldValue('content');
var renderer=nlapiCreateTemplateRenderer();
renderer.setTemplate(emailSubj);
renderSubj=renderer.renderToString();
renderer.setTemplate(emailBody);
renderBody=renderer.renderToString();
nlapiSendEmail(emailSendID,'noreply#xxxxx',renderSubj,renderBody,finalEmailArray,bccEmailArray);
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.
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)
})
I am using node.js 's email module nodemail and sendgrid API to send the email to the users.
Here is my code for sending a email
SOURCE_EMAIL = ?????;
var options = {
auth: {
api_user: sendgrid.api,
api_key: sendgrid.key
}
};
transport = nodemailer.createTransport(sgTransport(options));
transport.sendMail({from: SOURCE_EMAIL, to: email, subject: subject, html: html}, function(err,data){
});
my question is when I use the sendgrid API to send email, what SOURCE_MAIL i should configure to ?
You may set SOURCE_EMAIL to anything you want.
It's best to set it to an email you own, control, and can receive email from.
However, it's entirely up to you.