How to send mandrill emails to array of emails? - javascript

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

Related

Cannot charge a customer that has no active card

So I am getting the error in Stripe that "Cannot charge a customer that has no active cards".
I am using node js for this
Payment Code is given below
try {
const customer = await stripe.customers.create({
email: req.body.email,
source: req.body.id,
});
const payment = await stripe.charges.create(
{
amount: req.body.totalAmount * 100,
currency: "inr",
customer: customer.id,
receipt_email: req.body.email,
confirm: true,
off_session: true,
},
{
idempotencyKey: uuidv4(),
}
);
And I am getting the following error
type: 'StripeCardError',
raw: {
code: 'missing',
doc_url: 'https://stripe.com/docs/error-codes/missing',
message: 'Cannot charge a customer that has no active card',
param: 'card',
type: 'card_error',
}
Log out req.body.id as that might be null and then investigate why your frontend is not passing that parameter to your backend.
Second, confirm and off_session are not supported parameters on the /v1/charges endpoint.

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
}
});

Can't create subscriptions on Stripe

I can't create stripe subscription due to Missing required param: items.. I request it with items although.
The error:
{
"error": {
"code": "parameter_missing",
"doc_url": "https://stripe.com/docs/error-codes/parameter-missing",
"message": "Missing required param: items.",
"param": "items",
"type": "invalid_request_error"
}
}
The code:
const stripeCustomer = await stripe.customers.create({
name: name,
email: email,
plan: basicPlan,
})
const stripeSubscription = await stripe.subscriptions.create({
items: [{ plan: basicPlan }],
customer: stripeCustomer.id,
})
Stripe Customer account was successfully added.
Got the same problem. I've found out I'm lacking some package details

Merge an Item Fulfillment with an advanced template and email it Netsuite 2.0

So without the merge function below, this code sends an email on save, but I cannot for the life of me get email merge to work in Netsuite 2.0, so how do I merge an advanced pdf template with an item fulfillment and email it?
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(['N/email','N/render', 'N/record', 'N/file'],
function(email, record, file,render) {
function afterSubmit(context) {
function templatemerge() {
var myMergeResult = render.mergeEmail({
templateId: 121,
entity: {
type: 'employee',
id: 18040
},
recipient: {
type: 'employee',
id: 18040
},
supportCaseId: 'NULL',
transactionId: 1176527,
customRecord: 'NULL'
});
}
templatemerge();
function sendEmailWithAttachement() {
var newId = context.newRecord;
var emailbody = 'attachment';
var senderId = 18040;
var recipientEmail = 'email#email.com';
email.send({
author: senderId,
recipients: recipientEmail,
subject: 'Item Fulfillments',
body: emailbody
});
}
sendEmailWithAttachement();
}
return {
afterSubmit: afterSubmit
};
});
Try rearranging the first function signature to function(email, render, record, file)
They are probably in the wrong order.

Sails.js Mandrill api error

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);
}
});

Categories