问题
I am using sendgrid to send an email. I want to send template as an email to users. Below code is just sending the simple text based email instead of defining the headers part and using the template id.
if (Meteor.isServer) {
Email.send({
from: "from@mailinator.com",
to: "abc@mail.com",
subject: "Subject",
text: "Here is some text",
headers: {"X-SMTPAPI": {
"filters" : {
"template" : {
"settings" : {
"enable" : 1,
"Content-Type" : "text/html",
"template_id": "3fca3640-b47a-4f65-8693-1ba705b9e70e"
}
}
}
}
}
});
}
Your help will highly be appreciated.
Best
回答1:
To send SendGrid transactional templates you have different options
1) Via the SendGrid SMPT API
In this case we can use Meteor email package (as you were trying).
To add meteor email package we need to type in the sell:
meteor add email
In this case, according to SendGrid docs:
The
text
property is substituted into the <%body%> of the text template andhtml
is substituted into the <%body%> of the HTML template. If thetext
property is present, but nothtml
, then the resulting email will only contain the text version of the template, not the HTML version.
So in your code you need to provide http
property too, that's all.
This could be your server code:
// Send via the SendGrid SMTP API, using meteor email package
Email.send({
from: Meteor.settings.sendgrid.sender_email,
to: userEmail,
subject: "your template subject here",
text: "template plain text here",
html: "template body content here",
headers: {
'X-SMTPAPI': {
"filters": {
"templates": {
"settings": {
"enable": 1,
"template_id": 'c040acdc-f938-422a-bf67-044f85f5aa03'
}
}
}
}
}
});
2) Via the SendGrid Web API v3
You can use meteor http
package to use SendGrid Web API v3 (here docs). In this case we can use the Meteor http package.
To add Meteor http package type in the shell:
meteor add http
Then in your server code you can use
// Send via the SendGrid Web API v3, using meteor http package
var endpoint, options, result;
endpoint = 'https://api.sendgrid.com/v3/mail/send';
options = {
headers: {
"Authorization": `Bearer ${Meteor.settings.sendgrid.api_key}`,
"Content-Type": "application/json"
},
data: {
personalizations: [
{
to: [
{
email: userEmail
}
],
subject: 'the template subject'
}
],
from: {
email: Meteor.settings.sendgrid.sender_email
},
content: [
{
type: "text/html",
value: "your body content here"
}
],
template_id: 'c040acdc-f938-422a-bf67-044f85f5aa03'
}
};
result = HTTP.post(endpoint, options);
来源:https://stackoverflow.com/questions/47217847/trigger-sendgrid-template-email-using-meteor