Sending HTML emails from Node.JS using MailGun - javascript

I send email notifications to my users from my app but currently I only send it as a text. I would like to send it HTML emails which are styled.
Currently I tried this:
var data = {
from: 'my app',
to: user.email,
subject: 'Welcome',
html: '<div style="width: 500px; height: 400px: background: #ebebeb; color: #ddd"><p>Hi + "user.firstName" + \n ,this email is to inform you that has added their bio to the knowledge Base \n</p></div>'
};
Compiling the above code does not work, it does not like the styles I have put in.
I have created a separate HTML file within my local directory for each type of email I want send and I would like to be able to attach that html file to my email.
Something like this:
var data = {
from: 'my app',
to: user.email,
subject: 'Welcome',
html: welcomeToSiteEmail.html
};
Is the above possible? Any help will be greatly appreciated.

You can use mailgun-js together with mailcomposer to send HTML formatted emails.
The mailgun-js docs include an example:
var domain = 'mydomain.mailgun.org';
var mailgun = require('mailgun-js')({ apiKey: "YOUR API KEY", domain: domain });
var mailcomposer = require('mailcomposer');
var mail = mailcomposer({
from: 'you#samples.mailgun.org',
to: 'mm#samples.mailgun.org',
subject: 'Test email subject',
body: 'Test email text',
html: '<b> Test email text </b>'
});
mail.build(function(mailBuildError, message) {
var dataToSend = {
to: 'mm#samples.mailgun.org',
message: message.toString('ascii')
};
mailgun.messages().sendMime(dataToSend, function (sendError, body) {
if (sendError) {
console.log(sendError);
return;
}
});
});

Alternately, you could check out nodemailer on npm. It's a great package: easy to use and extensive documentation. With nodemailer, you can do something like this
var nodemailer = require('nodemailer');
var transport = nodemailer.createTransport({
host: 'smtp.mailgun.org',
port: 587,
secure: false,
tls: { ciphers: 'SSLv3' },
auth: {
user: '<Mailgun SMTP login>',
pass: '<Mailgun SMTP password>'
}
});
transport.sendMail({
from: '<Mailgun SMTP login>',
to: ['bob#example.com', 'bill#foobarbaz.com', /*etc*/],
subject: 'Fancy Email',
text: 'still send some text to be on the safe side',
html: { path: 'path/to/email.html' }
}, callback)
// also returns a promise.
However, I would suggest being very thorough in your design of html emails. Writing html email is very different from html in the web. There's a much wider variety of email clients that do will render your html differently, and some, Outlook for Windows and gmail web for example, will not treat your html very nicely. Litmus has some nice resources regarding best practices for designing html emails.
My suggestion would be to use foundation for emails for your styling, use inky to simplify the semantics of writing html email, and inline-css to inline all of your styles. Even if you use alternate methods of sending the mail, check out these resources for designing it. They will save you lots of headache.

Related

Can you retrieve the emails of users in the Active Directory (ExpressJS)?

Thus far I was able to get the username and password of people for authentication, but I want to also find their emails. Is it even possible? If yes, How can this be done?
Below is the code for the AD config:
const activedirectory_config = {
url: process.env.ACTIVEDIRECTORYURL,
baseDN: process.env.ACTIVEDIRECTORYBASEDN,
username: process.env.ACTIVEDIRECTORYUSERNAME,
password: process.env.ACTIVEDIRECTORYPASSWORD,
};
The values are in the dotenv file.

template literals formatting when sending mail

im sending emails using nodemail and sendgrid. ive structured my email message as the code below but when it is received it looks like that attached image, how can i make the text all align to the left and look normal.
my code
var mailOptions = {
to: admin.email,
from: 'noreply#123.co.uk',
subject: 'Admin Account set up',
text: `Dear ${admin.name} ${admin.surname},
You are receiving this email because your organisation has added you as an admin. To complete the set up, please
use the link below to set a new password and sign in.
https://${req.headers.host}/reset/${token}
Sincerely,
HR Team
This email was automatically generated by 123
`
};
the output:
var mailOptions = {
to: admin.email,
from: 'noreply#123.co.uk',
subject: 'Admin Account set up',
text:
`Dear ${admin.name} ${admin.surname},
You are receiving this email because your organisation has added you as an admin. To complete the set up, please
use the link below to set a new password and sign in.
https://${req.headers.host}/reset/${token}
Sincerely,
HR Team
This email was automatically generated by 123`
}

How to generate Cloudinary Authentication signatures in PHP(Laravel)

I use Cloudinary with Laravel and I want to let users to choose from the existing files or upload new. How can I generate authentication signatures on the BackEnd(php in my case)? and pass it to the front end (JavaScript)?
I've tried to use unsigned upload preset to let users upload without requiring them to be signed in, but no luck.
mediaWidget = cloudinary.createMediaLibrary({
cloud_name: "my-cloud-name",
api_key: 'my-api-key',
username: 'email id',
uploadPreset: "unsigned-upload-preset",
multiple: false,
}, {
insertHandler: function (data) {
data.assets.forEach(asset => { console.log("Inserted asset:",
JSON.stringify(asset, null, 2)) })
}
}
);
I'm getting no error, but it always require user to login into cloudinary account
You can use any SHA-256 hashing function/library to create the signature using the values (cloud name, timestamp, username) mentioned in the documentation. Using PHP as an example, the example in the Media Library documentation looks like this:
<?php
$cloud_name = 'my_company';
$timestamp = '1518601863';
$username= 'jane#mycompany.com';
$api_secret = 'abcd';
$payload_to_sign = 'cloud_name='.$cloud_name.'&timestamp='.$timestamp.'&username='.$username;
$signature = hash('sha256', $payload_to_sign . $api_secret);
print($signature);
?>
This provides the same output as the documentation example: 5cbc5a2a695cbda4fae85de692d446af68b96c6c81db4eb9dd2f63af984fb247
Then, in the Javascript code used to initiate the Media Library widget, you pass the same timestamp, and the signature from the server-side code, and it should open and log you in as the specified user:
window.ml = cloudinary.createMediaLibrary({
cloud_name: 'my_company',
api_key: '1234567890',
username: 'jane#mycompany.com',
timestamp: '1518601863',
signature: '5cbc5a2a695cbda4fae85de692d446af68b96c6c81db4eb9dd2f63af984fb247'
}, function(error, result) {
console.log(error, result)
});
You need to use the Cloudinary PHP SDK or there is a Cloudder, a Laravel wrapper for Cloudinary which has some nice helpers although it doesn't cover every use case.
The Cloudinary documentation covers image and video upload using the PHP SDK.

get email from user in nodemailer

I have a contact form using Nodemailer.
This is my code:
let mailOptions = {
from: '<xxx#xxx.com>', // sender address
to: 'xxx#xxx.com', // list of receivers
subject: 'Kontaktanfrage', // Subject line
html: output // html body
};
In the from I have set up my email but I actually want to see email from the user in my inbox.
Can someone help me to do it?
I would appreciate your help!
Node-mailer is used to send the messages you can also check this reference
there are other packages that works for you, you can check these, it might be your workaround
1.node-mailin
2. mailin

Have a Microsoft Azure web app chatbot proactively contact a user using e-mail or Twilio from a table/list of preset users

I have a simple web app chatbot made with Azure. It is very simple, it will ask a user 3 questions, record the answers to a storage table and repeat the answers back to the user.
I have connected it to Twilio and e-mail using the Channels tab in azure portal. I wonder, is it possible to have a table or database with e-mail addresses or phonenumbers that the bot will contact, preferably if perhaps a variable for a certain address switched from false to true that address would be contacted.
This is the closest example I have found however it uses Skype. Not e-mail or Twilio. https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/core-CreateNewConversation
I would like something like this part
// Every 5 seconds, check for new registered users and start a new dialog
setInterval(function() {
var newAddresses = userStore.splice(0);
newAddresses.forEach(function(address) {
console.log('Starting survey for address:', address);
// new conversation address, copy without conversationId
var newConversationAddress = Object.assign({}, address);
delete newConversationAddress.conversation;
// start survey dialog
bot.beginDialog(newConversationAddress, 'survey', null, function(err) {
if (err) {
// error ocurred while starting new conversation. Channel not supported?
bot.send(new builder.Message()
.text('This channel does not support this operation: ' + err.message)
.address(address));
}
});
});
to scan a table and if a variable switches it will extract the address from the table and set it as a address variable.
I believe I can figure that out myself however I require help to learn how to make the bot contact a user without the user contacting the bot first, instead using a list of preset users.
If there is any documentation regarding the e-mail channel for a web app bot I have not been able to find it, I would like to know how to have the bot send a e-mail to a user and if there are any JavaScript classes I could use to use the e-mail channel in my bots app.js code.
I hope I made myself understandable, many thanks for any help
With regard to contacting a user without them having first contacted the bot on the Email and Twilio channels you can do the following.
Set up the addresses for each like so:
Email
var emailAddress =
{
channelId: 'email',
user: { id: <userEmail> },
bot: { id: <botEmail>, name: <botName> },
serviceUrl: 'https://email.botframework.com/'
};
SMS
var sms =
{
user: { id: '<userphone>' },
bot: { id: '<botphone>' },
conversation: {id: '<userphone>'},
channelId: 'sms',
serviceUrl: 'https://sms.botframework.com'
};
Note that SMS will not work with a trial twilio number, but will work fine with a purchased number.
After you have your addresses set up, you can route each of them through something like the following code.
var message = new builder.Message()
.address(address)
.text(<messageText>);
try {
console.log(message);
bot.send(message);
} catch (error) {
console.log(error);
}
Will edit this to include loading the user list later if needed.

Categories