Sails.js Mandrill api error - javascript

I'm using the sails-mandrill module for a sails.js app. I'm having trouble sending the email. I keep getting this error:
to must be specified, e.g.:
{ to: { email: "foo#bar.com", name: "Mr. Foo Bar" } }
I have my code formatted exactly like that and can't figure out why its still giving me the error.
var email = require('sails-mandrill');
var recipients = [{
email: 'name#email.com',
name: 'John Smith'
}];
email.send({
to: recipients,
subject: 'Test Email',
html:
'I can\'t wait to see you all in Chicago<br/>' +
'I loe you so much!!!! ',
text: 'text fallback goes here-- in case some recipients (let\'s say the Chipettes) can\'t receive HTML emails'
}, function optionalCallback (err) {
if (err) {
console.log(err);
}
});

Related

Sending Case Reply Email With Proper Reply-To in SuiteScript

I have some functionality that automatically sends an email response when a case is created via someone submitting an email that gets sent to a NetSuite case profile email address. The trouble comes when attempting to set a proper reply-to email address. So far the attempts at creating one don't allow for a successful response directly back into the case record. At first undeliverable messages were being returned until I found an error made in the structure of the address. Now, however, the messages don't appear to make it back to the case records. This is the structure being used:
cases.AAAAA.BBBBB_CCCCC_DDDDD.EEEEE#AAAAA.email.netsuite.com
// AAAAA is the account number
// BBBBB is the internal ID of the case record
// CCCCC is the internal ID of the message record
// DDDDD is the internal ID of the customer record on the case
// EEEEE is a hexadecimal value of unknown sourcing or meaning
I'm thinking maybe part of the problem is that the message record ID is the ID of the message that was sent out from the case, and with what I've been doing it's the ID of the message record saved from the initial incoming email that generated the case in the first place. This leads me to believe that I can't just use the email.send() API with setting a reply-to email address, but I don't see another way to send out the email. Is there anything that I'm missing?
You do not use the email.send() function if you intend on having the customer be able to reply to a Support Case.
Instead, you need to create a Case record (or load an existing one) and then send your email message through that Case record.
Upload the following example script to your File Cabinet and create a Suitelet script, deploy it, and run it. You'll see a simple form that allows you to send out an email via a Case record.
EXAMPLE SCREENSHOT:
CODE:
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
*/
define(['N/ui/serverWidget', 'N/ui/message', 'N/record', 'N/url', 'N/email'], function (serverWidget, message, record, url, email) {
function onRequest(context) {
var form = serverWidget.createForm({
title: 'Send Email via Support Case'
});
form.addField({
id: 'custom_customer',
label: 'Customer',
type: serverWidget.FieldType.SELECT,
source: record.Type.CUSTOMER
});
form.addField({
id: 'custom_email',
label: 'Email Address (not required)',
type: serverWidget.FieldType.TEXT
});
form.addField({
id: 'custom_messagesubject',
label: 'Message Subject',
type: serverWidget.FieldType.TEXT
});
form.addField({
id: 'custom_messagebody',
label: 'Message Body',
type: serverWidget.FieldType.RICHTEXT
});
form.addSubmitButton({
label: 'Send Email'
});
if (context.request.method === 'POST') {
var customerId = context.request.parameters['custom_customer'];
var customerEmail = context.request.parameters['custom_email'];
var messageSubject = context.request.parameters['custom_messagesubject'];
var messageBody = context.request.parameters['custom_messagebody'];
try {
var caseId = 0;
var errorMsg = '';
var caseRec = record.create({
type: record.Type.SUPPORT_CASE
});
caseRec.setValue({
fieldId: 'company',
value: customerId
});
// You can specify an email address to overide the customer's default
// Useful if you need to use an "Anonymous Customer" record and set the outgoing email address to the correct one
if (customerEmail != '') {
caseRec.setValue({
fieldId: 'email',
value: customerEmail
});
}
caseRec.setValue({
fieldId: 'title',
value: messageSubject
});
caseRec.setValue({
fieldId: 'emailform',
value: true
});
caseRec.setValue({
fieldId: 'outgoingmessage',
value: messageBody
});
caseId = caseRec.save({
ignoreMandatoryFields: true
});
} catch (e) {
errorMsg = JSON.stringify(e);
}
if (caseId > 0 && errorMsg == '') {
var caseUrl = url.resolveRecord({
recordType: record.Type.SUPPORT_CASE,
recordId: caseId
});
form.addPageInitMessage({
message: 'Email sent successfully. <a target="_blank" href="' + caseUrl + '">Open Support Case</a>',
title: "Success!",
type: message.Type.CONFIRMATION
});
} else {
form.addPageInitMessage({
message: "Error occurred while sending case message: " + errorMsg,
title: "Failed",
type: message.Type.ERROR
});
}
}
context.response.writePage(form);
}
return {
onRequest: onRequest
};
});
Using the relatedRecords.activityId will automatically send the email with case reply to address.
email.send({
author: me.id,
recipients: you.id,
subject: 'New Case',
body: emailBody,
// attachments: [fileObj],
relatedRecords: {
activityId: thisCase.id
}
});

How to send mandrill emails to array of emails?

I'm building an app in Node and I'm using mandrill to send emails every time there is a new user to a predefined array of emails. I have an array of emails:
And I have this function where
newUserEmail(user_name, email) {
emailArray = [example1#ex.com, example2#ex.com, example3#ex.com]
const message = {
html: '<p>Name: *|NAME|* <br> Email: *|EMAIL|*</p>',
text: 'Name: *|NAME|*, Email: *|EMAIL|*',
subject: 'New person arrived',
from_email: 'newperson#example.com',
from_name: 'New',
to: [{
email: emailArray,
type: 'to'
}],
merge: true,
merge_vars: [{
rcpt: emailArray,
vars: [{
name: 'NAME',
content: user_name
}, {
email: 'EMAIL',
content: email
}]
}]
};
mandrill_client.messages.send({ message }, function(result) {
console.log(result);
}, function(e) {
console.log(`A mandrill error occurred: ${e.name} - ${e.message}`);
});
}
I get this on my console:
[ { email: 'Array',
status: 'invalid',
_id: '...',
reject_reason: null } ]
If I set only one email, it gets sent without problems.
Do I need to make a loop and run this function as many times as there are emails in the array? I hoped mandrill would recognise emails in the array :(
From what I gathered after a look at the documentation it looks like each object in the "to" array is an individual email address.
I would not run the function for each email address. Just map over the email array.
For example:
const formattedArray = emailArray.map(email => ({ email, type: 'to' }));
// if you're not a fan of arrow functions
const formattedArray = emailArray.map(function(email) {
return { email, type: 'to' };
});
Then in the mandrill message you can just set "to" equal to the formattedArray
to: formattedArray

Formatting an email in JavaScript and SendGrid

I'm trying to pass a formatted string into my function, but when the email is sent the text does not appear line by line, which is what I want.
var bodySummary = nominatorName + "\n" + nominatorRegion
// Run email Cloud code
Parse.Cloud.run("sendEmail", {
toEmail: "test#gmail.com",
subject: "Email Test",
body: bodySummary
}).then(function(result) {
// make sure to set the email sent flag on the object
console.log("result :" + JSON.stringify(result));
}, function(error) {
// error
});
I'm using SendGrid and Parse Cloud Code to generate emails in my web app:
Parse.Cloud.define("sendEmail", function(request, response) {
// Import SendGrid module and call with your SendGrid API Key
var sg = require('sendgrid')('API_KEY');
// Create the SendGrid Request
var reqSG = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
personalizations: [
{
to: [
{
// This field is the "to" in the email
email: request.params.toEmail,
},
],
// This field is the "subject" in the email
subject: request.params.subject,
},
],
// This field contains the "from" information
from: {
email: 'no-reply#test.com',
name: 'Test',
},
// This contains info about the "reply-to"
// Note that the "reply-to" may be different than the "from"
reply_to: {
email: 'no-reply#test.com',
name: 'Test',
},
content: [
{
// You may want to leave this in text/plain,
// Although some email providers may accept text/html
type: 'text/plain',
// This field is the body of the email
value: request.params.body,
},
],
},
});
// Make a SendGrid API Call
sg.API(reqSG, function(SGerror, SGresponse) {
// Testing if some error occurred
if (SGerror) {
// Ops, something went wrong
console.error('Error response received');
console.error('StatusCode=' + SGresponse.statusCode);
console.error(JSON.stringify(SGresponse.body));
response.error('Error = ' + JSON.stringify(SGresponse.body));
}
else {
// Everything went fine
console.log('Email sent!');
response.success('Email sent!');
}
});
});
The end result email should look like this:
nominatorName
nominationRegion
Currently, it looks like this:
nominatorName nominatorRegion
There could be two ways to accomplish.
Using HTML Body
var bodySummary = nominatorName + "<br>" + nominatorRegion
Using newline escape characters
var bodySummary = nominatorName + "\r\n" + nominatorRegion
You need to replace the line break character \n with the HTML line break <br>.
For example:
var bodySummary = nominatorName + '<br>' + nominatorRegion;

emailjs not working [node js]

i'm trying to use the emailjs (https://github.com/eleith/emailjs) for send emails with nodejs, but, it gives me an error: { [Error: timedout while connecting to smtp server] code: 4, smtp: undefined }
I'm trying to use hotmail, but I can use other, I only want this working. Any idea please?
var email = require("emailjs");
var server = email.server.connect({
user: "xxx#hotmail.com",
password:"xxxyyyy",
host: "smtp-mail.live.com",
ssl: true
});
// send the message and get a callback with an error or details of the message that was sent
server.send({
text: "i hope this works",
from: "you <xxxxxx#hotmail.com>",
to: "someone <zzzzz#hotmail.com>",
//cc: "else <else#your-email.com>",
subject: "testing emailjs"
}, function(err, message) { console.log(err || message); });
I tested with the code below (using gmail) and it is working:
var email = require('emailjs');
var server = email.server.connect({
user: 'nodejsiscool#gmail.com',
password: 'stackoverflow',
host: 'smtp.gmail.com',
ssl: true
});
server.send({
text: 'Hey howdy',
from: 'NodeJS',
to: 'Wilson <wilson.balderrama#gmail.com>',
cc: '',
subject: 'Greetings'
}, function (err, message) {
console.log(err || message);
});
In my console the output is:
{
attachments: [],
alternative: null,
header: {
'message-id': '<1433256538447.0.5970#Wilsons-MacBook-Pro.local>',
date: 'Tue, 02 Jun 2015 10:48:58 -0400',
from: '=?UTF-8?Q?NodeJS?= <>',
to: '=?UTF-8?Q?Wilson?= <wilson.balderrama#gmail.com>',
cc: '',
subject: '=?UTF-8?Q?Greetings?='
},
content: 'text/plain; charset=utf-8',
text: 'Hey howdy'
}
Indeed I have received in my inbox the email message.
I suspect that you should use the host smtp.live.com instead of smtp-mail.live.com
Note: The account (nodejsiscool#gmail.com) used is a valid one I just created for testing purposes.
Using Gmail
First: Required activate the use less secure apps at your own risk as indicated in the Gmail documentation. I use an account not very important for my tests:
https://myaccount.google.com/u/2/lesssecureapps?pageId=none
After:
var email = require("emailjs");
var server = email.server.connect({
user: "YOUR_ACCOUNT#gmail.com",
password:"YOUR_PASSWORD",
host: "smtp.gmail.com",
ssl: true
});
server.send({
text: "Hello world",
from: "YOUR_NAME <YOUR_ACCOUNT#gmail.com>",
to: "FRIEND_NAME <FRIEND_ACCOUNT#gmail.com>",
subject: "Hello"
}, function(err, message) { console.log(err || message); });
Additional Note: About how set "from" and displayed name in Gmail inbox:
Example 1:
Set "from" with only name.
from: "YOUR_NAME", // Only name
In inbox display <>
YOUR_NAME <> Hello 18:11
Example 2:
Set "from" with name and emial.
from: "YOUR_NAME <YOUR_ACCOUNT#gmail.com>", // Name and email
In inbox not display <>
YOUR_NAME Hello 18:11
Make sure you are linking the emailjs files correctly (check var email) or it won't work.
//Email stuff
var email = require("./node_modules/emailjs/email");
var server = email.server.connect({
user: "EMAIL#gmail.com",
password:"INSERTPASSWORDHERE",
host: "smtp.gmail.com",
ssl: true
});
//If button is clicked then send email
server.send({
text: 'Hello World! \n\n Regards,\n INSERTNAMEHERE \n',
from: 'Name',
to: 'Name <EMAIL#gmail.com>',
cc: '',
subject: ''
}, function (err, message) {
console.log(err || message);
});
make sure you have installed exact package with same version
npm i emailjs#1.0.11
and try below code
var email = require("emailjs");
var server = email.server.connect({
user: "your-email#gmail.com",
password: "your-password",
host: "smtp.gmail.com",
ssl: true
});
server.send(
{
text: "Hey howdy",
from: "NodeJS",
to: "Wilson <your-email#gmail.com>",
cc: "",
subject: "Greetings"
},
function(err, message) {
console.log(err || message);
}
);
seems latest version is not working its using es6 exports "emailjs#1.0.11" but version still works fine .
also don't forget to enable less secure setting for email address you are using with password .
I think you can use this version
emailjs#2.2.0
,
For me, this is working in version 2.2.0
where version 3.0 and above will show the error.
npm i emailjs#2.2.0
here is the example

mc:edit do not work in Mailchimp template with Mandrill Javascript API

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.

Categories