I am new to programming and would like to send a template via the mandrill api. Sending a message works fine.
What do I have to change in my code to send a template?
In the mandrill documentation I see that I can call a template I have stored in my account with this
"template_name": "example template_name",
But I don't know how to integrate this properly in my code below.
I would appreciate any help you can give. For the purpose of understanding the easiest would be if you can show me how the code would have to look in order to send the template.
function log(obj) {
$('#response').text(JSON.stringify(obj));
}
var m = new mandrill.Mandrill('API Key');
var params = {
"message": {
"from_email":"example#domain.com",
"from_name": "FromExampleName",
"to":[{"email":"recipient1#domain.com", "name": "Name of Recipient"}],
"subject": "Mandrill API Test",
"html": "Sending a template doesn't work."
}
};
function sendTheMail() {
m.messages.send(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}
it's solved.
The template has to be included like this
var params = {
"template_name": "templatename",
"template_content": [
{
"name": "example name",
"content": "example content"
}
],
"message": {
"from_email":"example#domain.com",
"to":[{"email":"recipient#domain.com}],
"subject": "Subject line",
"text": "text in the message"
}
};
Then send like this
function sendTheMail() {
// Send the email!
m.messages.sendTemplate(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}
Related
I am working on a function to send emails to users, I already have my send mail function and it sends to a single user. I am trying to send to multiple users in an array now.
I am writing in Typescript and I am using mailgun as my email service provider
This is a sample send mail function:
const data = {
from: 'example#from.com',
to: 'example#reciever.com',
subject: 'Sample subject',
html: await email(), // I am getting the email template here
}
await mailgun.messages().send(data)
With the code above, I am sending email to a single user. The json below shows how I am receiving the list of emails:
[
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
]
I want to be able to send to multiple users and I want to do it the smart way. Please suggest the best solution with code if possible.
Thank you.
Assuming the send function is async and returns a promise:
async function sendMail(){
const myRecipients = [
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
]
const fromAddress = "my#email.address"
// map our recipient array to the message format expected by `send`
const myMessages = myRecipients.map(r => ({
from: fromAddress,
to: r.email,
subject: "somesubject",
html: "some html"
}))
// map our messages to a bunch of "in-flight" promises
const promises = myMessages.map(m => mailgun.messages().send(m))
// wait for all the promises to complete
await Promise.all(promises)
}
I assume you're using mailgun-js, which seems to have something called mailing list which you possibly could utilize. If not, then I would suggest that rather than simply iterating the users list and sending one email at the time (synchronously with await), trigger all emails to be sent asynchronously and then use Promise.all to know when all has been sent. Sample below is by no means tested (as i've never used mailgun) but it should give you an idea on how to implement it.
const users = [
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
];
const sendEmailToUser = async (user) => {
const data = {
from: 'example#from.com',
to: 'example#reciever.com',
subject: 'Sample subject',
html: 'await email()'
};
await mailgun.messages().send(data);
};
(async () => {
const sendEmailPromises = [];
for(const user of users) {
// Start sending all emails
sendEmailPromises.push(sendEmailToUser(user));
}
// Wait for all emails to be sent
await Promise.all(sendEmailPromises);
// Do something
})()
You will have to iterate the data structure anyway.
var users = [
{
"name": "User 1",
"email": "user1#gmail.com"
},
{
"name": "user 2",
"email": "user2#gmail.com"
}
];
users.forEach(function(user){
name = user.name;
email = user.email;
var data = {
from: 'example#from.com',
to: email,
subject: 'Sample subject',
html: await email(),
}
await mailgun.messages().send(data);
});
use a array map
i dont know about typescript.
you can get all elements like this
for ES6
user_list.map(user => console.log(user.name, user.email))
I'm trying to access the Google Classroom API with Javascript and am running into a syntax problem when trying to create a student.
The relevant code is
function createStudent () {
var course_id = '146694xxx'
var enrollment_code = '7ytxxx'
var student = {
userId: 'xxx#gmail.com'
}
student = gapi.client.classroom.courses.students.create({courseId:course_id,enrollmentCode:enrollment_code, params: student}).execute();
}
The problem is with the named parameter for the student object. It is where I have "params". I have tried every name I can think of like requestBody, body and a million others. The error I get is
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"params\" at 'student': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "student",
"description": "Invalid JSON payload received. Unknown name \"params\" at 'student': Cannot find field."
}
]
}
]
}
}
How should I be representing that request body object in the call?
Thanks.
Harry
I'm trying to send emails through the Mandrill API with Mailchimp templates. I am doing this in the cloud code with Parse.com, see here https://www.parse.com/docs/cloud_modules_guide#mandrill. The emails are sent just fine, however, the mc:edit fields are never updated. This is the only content in the template now:
<span mc:edit="ship_id">ship_id</span>
This is what my call in Javascript looks like, hope somebody sees my mistake. I'm running this in Parse.com cloud code if that makes any difference. Thanks a lot!
var Mandrill = require('mandrill');
Mandrill.initialize('api-key');
Mandrill.sendTemplate({
template_name: "Drip campaign",
template_content: [{
name: "ship_id",
content:"Test Test"
}],
message: {
text: "Hi",
subject: "You have new mail",
from_email: "info#example.com",
from_name: "Thomas",
to: [
{
email: "answer#example.com",
name: "Fred"
}
],
"headers": {
"Reply-To": "answer#example.com"
},
"important": false,
"track_opens": true,
"track_clicks": true,
},
async: true
},{
success: function(httpResponse) {
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
}
Ok, so there is nothing wrong with my code, but it seems like the templates are not sent properly from Mailchimp to Mandrill as adding fields such as |NAME| for merge tages or mc:edit="name" just were not populated. At least the code of the Mailchimp template is pretty weird and very nested.
For that reason, I would recommend using your own HTML here, where you enter the merge tages or mc:edits https://mandrillapp.com/templates/.
As far as I understand from your question that you want to send e-mail at the same time you want to dynamically edit the mail content. As you have already used, you can do it via the Mandrill API. I suggest you to use the js files which are downloadable in the link;
https://github.com/jlainog/parse-mandrill-sendTemplate
From the js file in the github account, you can dynamically edit the mail content(must be in your template) via using the tag mc:edit.
For my case working copy of code is below;
Parse.Cloud.define("sendMail", function(request, response) {
var Mandrill = require('cloud/mandrillSend.js');
var sentTo = //Mail address to sent
var subject = //Mail Subject
var fromEmail = //From email
var fromName = //From Name
var sentToName = //Parameters from request
var fullName = //Full Name
Mandrill.initialize('YOUR MANDRILL API KEY');
Mandrill.sendTemplate({
template_name: "MANDRIL TEMPLATE",
template_content: [
{
name: "nameHeader",
content: sentToName,
},
{
name: "mail",
content: sentTo,
},
],
"key": "YOUR MANDRILL API KEY",
message: {
subject: subject,
from_email: fromEmail,
from_name: fromName,
to: [{
email: sentTo,
name: fullName
}],
important: true
},
async: false
}, {
success: function (httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function (httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
});
For example, in Mandrdil Template there is a span with the id;
<span mc:edit="mail"> test#gmail.com</span>
Hope this helps.
Regards.
I'm trying to create a public gist via javascript. I'm not using any authentication - this is all client-side.
var gist = {
"description": "test",
"public": true,
"files": {
"test.txt": {
"content": "contents"
}
}
};
$.post('https://api.github.com/gists', gist, function(data) {
});
The above code throws a 400: Bad Request - Problems parsing JSON. However, my JSON is valid. Any ideas?
Aha - I can't pass an object to $.post. It needs to be stringified first:
var gist = {
"description": "test",
"public": true,
"files": {
"test.txt": {
"content": "contents"
}
}
};
$.post('https://api.github.com/gists', JSON.stringify(gist), function(data) {});
I am trying to send message to Linked connections,how can send the message to 10 recipients and avoid the recipient to see the other recipients.
what is the property to add to Body Object??
var BODY = {
"recipients": {
"values": [
{
"person":
{
"_path": "/people/~",
}
},
{
"person":
{
"_path": "/people/RJO-_FYNp-",
}
},
{
"person":
{
"_path": "/people/U-GyYIV2ZU",
}
}
]
},
"subject": "Time line Cloud",
"body": "Hi All this is a test message im trying to use LinkedIn API and im so sorry if i bother you.\n http://goo.gl/OUvDP"
}
IN.API.Raw("/people/~/mailbox")
.method("POST")
.body(JSON.stringify(BODY))
.result(function error(e) { alert("Done"); })
.error(function error(e) { alert("Error"); });
There is no BCC setting for the member to member messages via the API at this time. You would need to send multiple messages, each to one person.