问题
I checked the SendGrid API docs, and didn't find a possibility to send bulk pre-rendered emails. Is this possible?
What I want to do is use my own templating engine to render the individual email content, and then upload these (including recipient, subject and the mail body) as bulk to the SendGrid systems.
I can send transactional mails without a problem, but it's currently too slow for large amounts of mails.
I'm currently using the Node.js library https://github.com/sendgrid/sendgrid-nodejs
回答1:
There are several possibilities. Generally to send a bunch of email quickly, I'd recommend the SMTPAPI which allows you to send up to 10,000 emails from one request. However, this requires using SendGrid's substitution system to customize the messages. Since you want to use your own templating system, this probably isn't the best option for you.
One thing I'd look toward is simply code optimizations, as in parallel sending a bunch of email probably shouldn't take too terribly long. Some of our biggest senders have been known to dump millions of emails at once through individual connections. Although, long term this may not be the best solution.
If neither of those answers work there is a way to send a bunch of email to SendGrid through one connection: SMTP. However, this will require removing the SendGrid Node Library and replacing it with NodeMailer (or some other SMTP library).
NodeMailer by default will keep connections open and alive so you can send multiple emails in one transaction. To do so, you'd do something like this:
var nodemailer = require("nodemailer");
// Create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "SendGrid",
auth: {
user: "your_username",
pass: "your_password"
}
});
// Let get the users you want to send email to
var users = getAllUsersAsArray();
// Loop through your users
users.forEach(function (user){
// Setup the message
var mailOptions = {
from: "You <you@example.com>",
to: user.email,
subject: subjectTemplate.render(user),
text: textTemplate.render(user),
html: htmlTemplate.render(user)
}
// Send mail
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});
});
If you still need to take advantage of parts of SendGrid's SMTPAPI, you may do so by using the SMTPAPI Node.js library and inserting its results into the header of your message.
var mailOptions = {
from: "You <you@example.com>",
to: user.email,
// Assuming you've created an smtpapi header instance named header
headers: header.jsonString(),
subject: subjectTemplate.render(user),
text: textTemplate.render(user),
html: htmlTemplate.render(user)
}
来源:https://stackoverflow.com/questions/24695750/is-it-possible-to-to-send-bulk-pre-rendered-email-via-the-sendgrid-api