Easy to understand example
Hello,
Would be great to provide an easy to understand example on your readme, something as simple as https://sendgrid.com/blog/migrating-app-sendgrids-template-engine/ for example, because tbh if I wanted to write 30 lines of javascript code to send a simple email I wouldn't be using sendgrid.
Your library is quite frustrating to use, even for an experienced developer.
Cheers, and sorry for this angry rant
ps: this example is exactly what I'm looking for https://sendgrid.com/docs/Integrate/Code_Examples/v2_Mail/nodejs.html , so easy to use
Hello @julesbou,
Angry rants are fine with me, especially if they have solutions attached :)
Thank you for taking the time to let us know.
We are currently planning the improvements for the next iteration, so you had good timing!
If you have any other particular requests, please let us know either in this thread or please open additional issues.
Thanks!
How do we use the helper class? All I wanna do is set the from name??
@jsgandalf,
Easiest way is: https://github.com/sendgrid/sendgrid-nodejs#hello-email, specifically: https://github.com/sendgrid/sendgrid-nodejs/blob/master/examples/helpers/mail/example.js#L4
You can also just build your own json as follows: https://github.com/sendgrid/sendgrid-nodejs/blob/master/examples/mail/mail.js#L31 (here is an overview of the json: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html)
Thanks!
Very helpful! This should be on the readme!!
@jsgandalf @thinkingserious I too find the library quite frustrating to use. I am trying to send a template email. I found the examples here not very helpful. I am confused on how to set the "to" and "from" email addresses, and this code does not even send my email. I've been scratching my head for the past three days. Any help?
Thanks for the feedback @bcootner. Your request helps bump fixing this up the queue. This is an issue I'm itching to get done.
In the mean time, hopefully this example will help:
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
function helloTemplate(){
var helper = require('sendgrid').mail
from_email = new helper.Email("[email protected]")
to_email = new helper.Email("[email protected]")
subject = "Hello World from the SendGrid Node.js Library"
content = new helper.Content("text/plain", "some text here")
mail = new helper.Mail(from_email, subject, to_email, content)
// The constructor above already creates our personalization object
// -name- and -card- are substitutions in my template
substitution = new helper.Substitution("-name-", "Example User")
mail.personalizations[0].addSubstitution(substitution)
substitution = new helper.Substitution("-card-", "Denver")
mail.personalizations[0].addSubstitution(substitution)
mail.setTemplateId("YOUR_TEMPLATE_ID")
return mail.toJSON()
}
function send(toSend){
//console.log(JSON.stringify(toSend, null, 2))
//console.log(JSON.stringify(toSend))
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY)
var requestBody = toSend
var emptyRequest = require('sendgrid-rest').request
var requestPost = JSON.parse(JSON.stringify(emptyRequest))
requestPost.method = 'POST'
requestPost.path = '/v3/mail/send'
requestPost.body = requestBody
sg.API(requestPost, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})
}
send(helloTemplate())
Please reach out if you need additional help.
@thinkingserious Thanks for you time and thoughtful response. I have the following code:
var sg = require('sendgrid').SendGrid("SG.**** .. ***6o");
function welcomeTemplate() {
console.log("template")
var helper = require('sendgrid').mail
from_email = new helper.Email("[email protected]")
to_email = new helper.Email("[email protected]")
subject = "Hello World from the SendGrid Node.js Library"
content = new helper.Content("text/plain", "some text here")
mail = new helper.Mail(from_email, subject, to_email, content)
substitution = new helper.Substitution("-Name-", "bcootner")
mail.personalizations[0].addSubstitution(substitution)
mail.setTemplateId("5a****-*******-******-9") //The ID of my Transactional Template
return mail.toJSON()
}
function sendMail(toSend) {
console.log("Send")
var sg = require('sendgrid').SendGrid("SG.***....****o")
var requestBody = toSend
var emptyRequest = require('sendgrid-rest').request
var requestPost = JSON.parse(JSON.stringify(emptyRequest))
requestPost.method = 'POST'
requestPost.path = '/v3/mail/send'
requestPost.body = requestBody
sg.API(requestPost, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})
}
And then I call this code with sendMail(welcomeTemplate()) but that doesn't work. The "template" and "send" appear in the logs but the statusCode, body or headers do not show up, no emails are being received and nothing shows up on my dashboard.
After requestPost.body = requestBody could you please do console.log(JSON.stringify(requestBody)) and let me know what you get.
@thinkingserious After some debugging it seems like nothing gets printed to the log after the line var emptyRequest = require('sendgrid-rest').request. First "template" gets logged, then about 5 minutes later "send" gets printed (and if I uncomment the lines you commented in the send function those work fine). Is there something I'm missing for this require statement, I just did npm install sendgrid
Please try this:
A. Create a file called post.json with the following payload:
{"content":[{"type":"text","value":"Hello, World!"}],"from":{"email":"[email protected]"},"personalizations":[{"subject":"Hello, World!","to":[{"email":"[email protected]"}]}]}
B. Replace the example emails
C. Run the following command:
curl -X "POST" "https://api.sendgrid.com/v3/mail/send" \
-H "Authorization: Bearer $SENDGRID_API_KEY" \
-H "Content-Type: application/json" \
-d @post.json
D. Either replace $SENDGRID_API_KEY with your API KEY, or add your API Key to an environment variable called SENDGRID_API_KEY
@thinkingserious I received that test email, I was also able to get the Hello Test working fine, it's just these templates don't want to work.
EDIT: So I replaced var emptyRequest = require('sendgrid-rest').request with var emptyRequest = sg.emptyRequest() and that sends the email, there's just not any formatting from the template design or any images.
@bcootner,
Unfortunately, I can't reproduce your error, so I'm trying to help step through where there could be a problem. Since you can send an email via curl, that means your API key is good. Perhaps the Template ID has a problem?
If you remove mail.setTemplateId("5a****-*******-******-9") does the email send?
@thinkingserious So if I remove the setTemplateID it sends the test "Hello World from the SendGrid Node.js Library".
I'm not sure if you saw my edit, but by replacing var emptyRequest = require('sendgrid-rest').request with var emptyRequest = sg.emptyRequest() the text from my template does send, but there no formatting (no fonts, no images). I get the following print out now from the console.
2016-07-13T00:01:07.514157+00:00 app[web.1]: date: 'Wed, 13 Jul 2016 00:01:07 GMT',
2016-07-13T00:01:07.514159+00:00 app[web.1]: connection: 'close',
2016-07-13T00:01:07.514157+00:00 app[web.1]: date: 'Wed, 13 Jul 2016 00:01:07 GMT',
2016-07-13T00:01:07.514158+00:00 app[web.1]: 'content-type': 'text/plain; charset=utf-8',
2016-07-13T00:01:07.502390+00:00 app[web.1]: 202
2016-07-13T00:01:07.502454+00:00 app[web.1]:
2016-07-13T00:01:07.514155+00:00 app[web.1]: { server: 'nginx',
2016-07-13T00:01:07.514159+00:00 app[web.1]: connection: 'close',
2016-07-13T00:01:07.514161+00:00 app[web.1]: 'x-frame-options': 'DENY' }
Something makes me think it's a problem with 'text/plain', but I'm not sure. Thanks again!
Hey @bcootner, I have just experienced the same issue and been scratching my head for a few hours, but managed to solve it. It feels that there is too much unnecessary stuff needed before you can actually send the email, but here's my helper function to do that:
Params
- from (e.g '[email protected]')
- to (e.g '[email protected]')
- subject (e.g 'test subject')
- message (e.g 'test message')
- template (template id which you want to use)
- templateVariables (object, where key - variable in the email, value - value to replace it with)
{ ":name": "someName", ":email": "someEmail" }. Note that:emailand:nameis how I have set my variables in the email template, it can be-email-or whatever you have - success callback
- error callback
let sendTemplateMail = (from, to, subject, message, template, templateVariables, successCallback, errorCallback) => {
var sg = require('sendgrid').SendGrid(process.env.SENDGRID_API_KEY),
helper = require('sendgrid').mail,
content_text = new helper.Content("text/plain", message),
content_html = new helper.Content("text/html", message),
request = sg.emptyRequest(),
email_to = new helper.Email(to),
email_from = new helper.Email(from),
mail = new helper.Mail(email_from, subject, email_to, content_text),
personalization = new helper.Personalization();
personalization.addTo(email_to);
personalization.setSubject(subject);
mail.setTemplateId(template);
mail.addContent(content_html);
for(var key in templateVariables) {
if(templateVariables.hasOwnProperty(key)) {
var substitution = new helper.Substitution(key, templateVariables[key]);
personalization.addSubstitution(substitution);
}
}
mail.addPersonalization(personalization);
request.method = 'POST';
request.path = '/v3/mail/send';
request.body = mail.toJSON();
sg.API(request, (json) => {
if(json.statusCode >= 300) {
errorCallback(json);
} else {
successCallback(json);
}
});
}
The documentation indeed needs some refactoring, with basic, simple examples. Hope my function will help you out :)
@ByEmke thanks for your support! Could you please email us at [email protected] with you T-shirt size and mailing address?
With regards to the documentation, a refactor is on it's way as well as for the mail helper itself. We've been collecting all of your feedback and are excited about the next iteration.
Also, a big confusion is that you still need set the content when using template. Fortunately, that will change very soon (days).
@bcootner I think you nailed it. You need content_html = new helper.Content("text/html", message). Fortunately, this requirement is going away in a few days, our team is currently changing this behavior so that when you specify a template, you will no longer need to set the content.
@ByEmke @thinkingserious thanks for your help on this issue, I managed to get it to work with the following code last night:
var sg = require('sendgrid').SendGrid("SendGrid API Key" or <environment variable>)
function sendEmail(tempID){
var helper = require('sendgrid').mail;
from_email = new helper.Email("[email protected]")
to_email = new helper.Email("[email protected]")
subject = "Dummy Subject"
content = new helper.Content("text/html", "dummy content")
mail = new helper.Mail(from_email, subject, to_email, content)
substitution = new helper.Substitution("-name-", "User's Name")
mail.personalizations[0].addSubstitution(substitution)
mail.setTemplateId(tempID)
var requestBody = mail.toJSON()
var requestPost = JSON.parse(JSON.stringify(sg.emptyRequest()))
requestPost.method = 'POST'
requestPost.path = '/v3/mail/send'
requestPost.body = requestBody
sg.API(requestPost, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})
}
Thanks again!
I also feel that the docs are quite hard to follow, especially when using templates and some other features.
I prefer the request.body = {} syntax over the helper() syntax as this makes things more verbose and less easy to read (for me at least).
I spent quite some time going through the docs, testing changes, looking at your examples and trying again only to come here and find out that you do need to set content when using templates though the docs state otherwise. Argh. Stuff like this can drive you mad. Anyways kudos to @ByEmke for providing a working example.
@peterkuiper (or should I say Adam :))
Thanks for the feedback, we are very interested in how we can make the library docs better.
To be clear, are you referring to these? https://github.com/sendgrid/sendgrid-nodejs/blob/master/USAGE.md
With regard to the content issue (we heard all of you :)), this is just about fixed. We will deploying a release to the API that will not require the content to be set when using a template. We hope that change will make the template experience much better.
@thinkingserious I was checking out the docs on sendgrid.com (ie https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html) while I should have gone straight to Github. I skimped through the README of this repo, checked out the examples and totally missed USAGE.md (my bad). The USAGE.md file should be the one that should be put on on sendgrid.com as it has my preferred format :) Still not sure about some best practices when using templates but I hope I can figure that out myself or find it in the docs.
I was browsing that file and just found a random example of something that I find confusing:
var request = sg.emptyRequest()
request.queryParams["start_time"] = '1'
request.queryParams["limit"] = '1'
request.queryParams["end_time"] = '1'
request.queryParams["offset"] = '1'
request.method = 'GET'
request.path = '/v3/suppression/blocks'
sg.API(request, function (response) {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
})
What types are start_time, limit, end_time and offset and what do these mean? Are there more queryParams? And why isn't it request.body?
There is a link to the User Guide (which does not help at all) while there should have been a link to the API docs which clears things up https://sendgrid.com/docs/API_Reference/Web_API_v3/blocks.html.
So you have to go back and forth trying to figure out where to find the information you need.