Formatting an email in JavaScript and SendGrid - javascript

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;

Related

sending value of my textarea with graphql

I hope you all have a great day. I am coding my own personal website and I have a section called to contact me. The problem I have with this section is that I am trying to send my client email to my email and when I am trying to send their message to my server through Graphql I get this error
[
{
"message": "Syntax Error: Unterminated string.",
"locations": [
{
"line": 3,
"column": 123
}
]
}
]
the request I sent to my server is
'\n mutation{\n sendEmail(EmailInput: {name: "Test name", email: "Test#email.com",
subject: "this is test subject", message: "\n
this is the first line \nthis is the second line\nwhen I have multiple lines I have these problem\n
"}) {\n success\n message\n }\n }\n '
I don't know how to fix it I don't know why I get this error.
I used fetch to send my code backend :
const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}", message: "
${senderMessage.value}
"}) {
success
message
}
}
`;
const result = await fetch("http://localhost:2882/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: emailMutationQuery,
}),
});
const convertedResult = await result.json();
GraphQL supports variables, which can be used to supply input data separately from the query. The variables are just a separate JSON-encoded object. This avoids syntactic difficulties (and potential security risks!) from trying to embed the inputs directly in the query.
For this you'd write a fixed query, that declares and uses the variable, but doesn't depend on the per-request inputs
const emailMutationQuery = `
mutation SendEmail($emailInput: SendEmailInput!) {
sendEmail(EmailInput: $emailInput) {
success
message
}
}
`;
You'd then create a second object containing the variable(s). The top-level keys match what you declare in the GraphQL operation line, and their content matches the corresponding GraphQL input types.
const variables = {
emailInput: {
name: senderName.value,
email: senderEmail.value,
subject: senderSubject.value,
message: senderMessage.value
}
};
Note that this is an ordinary Javascript object, and we haven't quoted or escaped anything here.
Now when we make the request, we send the query and variables together
const result = await fetch("http://localhost:2882/graphql", {
...,
body: JSON.stringify({
query: emailMutationQuery,
variables: variables
})
});
Things like newlines in the message content will be escaped in the variables block, and get passed through correctly to the underlying GraphQL engine.
I actually find a solution for it but feel free to share your answers here. The solution I found for this problem was that you have to use JSON.stringify() for the textarea. you have to pass your textarea value to this function and js will take care of the rest. my code now looks like this
const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}",
message:${JSON.stringify(senderMessage.value)}}) {
success
message
}
}
`;
I hope this help you guys.

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

Parsing array of data and sending with nodemailer?

I've got an array of data that I want to send in a table using NodeMailer that looks something like:
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: 2016-11-18T19:08:41.662Z,
updatedAt: 2016-11-18T19:08:41.662Z,
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: 2016-11-16T17:56:21.696Z,
updatedAt: 2016-11-16T17:56:21.696Z,
id: 'B01IM0K0R2'
}]
What I am trying to do i to create a loop inside my HTML and then loop through the data. I did try the below, but it seems there are limitations on what I can do.
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>{{result.forEach((item) => {<tr><td>{{asin}}</a></td><td>{{url}</td><td>{{favourite}}</td><td>{{createdAt}}</td></tr>})}}</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
Could anyone point out where I am going wrong please and what I need to do to correct my problems.
It seems you have tried to use results.forEach((item) but you placed this inside the quotes 'result.forEach((item)' which is a string and won't execute at all.
You may have used this kind of syntax in your page when you used the view engines like jade, swig etc which will do the parsing for you. But here, you should call them manually to parse this kind of syntax.
Otherwise, you can do the parsing with the array function as below where I have used array.reduce which is handy and will do the parsing nicely.
You can try the same to generate the content and append it to the html as below.
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' +
content + '</tbody></table></div>' // html body
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: '2016-11-18T19:08:41.662Z',
updatedAt: '2016-11-18T19:08:41.662Z',
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: '2016-11-16T17:56:21.696Z',
updatedAt: '2016-11-16T17:56:21.696Z',
id: 'B01IM0K0R2'
}];
var content = results.reduce(function(a, b) {
return a + '<tr><td>' + b.asin + '</a></td><td>' + b.url + '</td><td>' + b.favourite + '</td><td>' + b.reatedAt + '</td></tr>';
}, '');
console.log(content);
/*
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' + content + '</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
*/

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

Displaying AJax response with Jquery in a div

I have an ajax form that posts to a php page, which processes the form, then posts the data to mysql and then returns the data to the console.
Since I am really new at this, I don't know how to get it to display the data on the page in a <li> or <div for each new record that is returned, just like this script does: http://www.sanwebe.com/assets/ajax-add-delete-record/
This is the data that is returned in the console:
Object {type: "success", message: "Your message has been sent, thank you.", record: Object}
message: "Your message has been sent, thank you."
record: Object
account_number: "1234567812345678"
balance: "1234"
bank_name: "test name"
customer_id: "12345"
id: 49
monthly: "123456"
This is the current script that brings it to the console:
jQuery(document).ready(function($) {
$('form.quform').Quform({
successStart: function (response) {
console.log(response);
}
}
);
Something like this:
jQuery(document).ready(function($) {
$('form.quform').Quform({
successStart: function (response) {
var r = response.record;
var html = '<li>Acct#: ' + r.account_number + '</li><li>Balance: ' + r.balance + '</li><li>Bank: ' + r.bank_name + '</li><li>Customer#: ' + r.customer_id + '</li>';
$("#ulID").html(html);
}
});
});

Categories