Using nodemailer with G suite - email

I have tried using nodemailer with gmail and it works. I tried to use the same code with my G suite name#mydomain.com email and there's bad credentials error. Is there an easy way to use nodemailer with G suite? because I want my business mail to be seen as sender.
this is the code I am using:
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'name#business.com',
pass: 'password'
}
});
exports.sendMail = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// getting dest email by query string
const dest = req.query.dest;
const mailOptions = {
from: 'Your Account Name <aegegwgwg#gmail.com>', // Something like: Jane Doe <janedoe#gmail.com>
to: dest,
subject: 'I\'M A PICKLE!!!', // email subject
html: `<p style="font-size: 16px;">Pickle Riiiiiiiiiiiiiiiick!!</p>
<br />
<img src="https://images.prod.meredith.com/product/fc8754735c8a9b4aebb786278e7265a5/1538025388228/l/rick-and-morty-pickle-rick-sticker" />
` // email content in HTML
};
// returning result
return transporter.sendMail(mailOptions, (erro, info) => {
if(erro){
return res.send(erro.toString());
}
return res.send('Sended');
});
});
});

Related

Strapi custom email template

I'm using nodemailer for email submission and running from my localhost. I have email services created manually in the following dir /api/email/services/Email.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'example.com',
port: 587,
secure: false,
auth: {
user: 'user',
pass: 'password',
},
});
module.exports = {
send: (from, to, subject, html) => {
const options = {
from,
to,
subject,
html
};
return transporter.sendMail(options);
},
};
So then I can use it like strapi.services.email.send(from, email, subject, html);
Usually, I write my html template in the code line const html = '<p>Email testing</p>' to be passed in the email services. But I don't want to do this for every email submission from different controllers.
So, I created a html template in /config/email-templates/custom-email.html and tried to call it like const html = path.join(__dirname + '/../../../config/email-templates/custom-email.html');.
When I run it, the email can be sent successfully but it cannot render the html. Instead of a rendered html, it's showing the full path of the custom-email.html as the email message. Is this method possible to achieve in strapi?
Instead of passing the path to the file, you need to pass the actual content. In the first case const html = '<p>Email testing</p>' , you are actually passing the content , but in the second case you are passing the file path.
Modified send method could look something like below:
send: (from, to, subject, htmlpath) => {
const readHTMLFile = (path, callback)=> {
fs.readFile(path, {encoding: "utf-8"}, function (err, html) {
if (err)
return callback(err);
else
return callback(null, html);
});
}
readHTMLFile(htmlpath, function(err, html) {
const options = {
from,
to,
subject,
html
};
return transporter.sendMail(options);
}); }

How to send mail with attachment in lambda nodeJs using SES service

I am trying to send a mail with attachment.
I have already used SES service for sending simple and HTML content mail. but now I want to send a mail with attachments.
I am using amazon SES service for sending emails and I am using the 'sendRawEmail' method for send mail with attachments.
I am getting an error message like this.InvalidParameterValue: Nested group
I didn't find any Node examples for this type of error.
I am having a very frustrating time trying to send emails with NodeJS SES API.
I found the issue and i fixed that with using mailcomposer npm package.
Now I an able to send a Mails with attachments.
Install AWS SDK
npm i aws-sdk
Now Install manilcomposer
npm i mailcomposer
Full code below
Request body:
if you want to send mail With Base64 content.
{
email: ['jen****#gmail.com', 'Aa****#gmail.com'],
from: 'no-reply#*****.com',
subject: 'Sending emails with attachments',
text: 'please find attachments',
attachments: [{
filename: 'sample.pdf',
content: {{file}}, // file content base64 staring
encoding: 'base64',
}]
}
if you want to send a mail with the file path.
{
email: ['jen****#gmail.com', 'Aa****#gmail.com'],
from: 'no-reply#*****.com',
subject: 'Sending emails with attachments',
text: 'please find attachments',
attachments: [{
filename: 'sample.pdf',
path: './home/sample,pdf'
}]
}
Business logic Code:
const ses = new AWS.SES({ region: 'us-east-1' }); //specify region for the particular see service.
const mailcomposer = require('mailcomposer');
exports.handler = function (event, context) {
console.log('Event: ',JSON.stringify(event));
if (!event.email) {
context.fail('Missing argument: email');
return;
}
if (!event.subject) {
context.fail('Missing argument: subject');
}
if (!event.from) {
context.fail('Missing argument: from');
}
if (!event.html && !event.text) {
context.fail('Missing argument: html|text');
}
const to = event.email;
const from = event.from;
const subject = event.subject;
const htmlBody = event.html;
const textBody = event.text;
const attachments = event.attachments;
const mailOptions = {
from: from,
subject: subject,
text: textBody,
html: htmlBody,
to: to,
attachments: attachments ? attachments : []
};
const mail = mailcomposer(mailOptions);
mail.build(function (err, message) {
const req = ses.sendRawEmail({ RawMessage: { Data: message } });
req.on('build', function () {
req.httpRequest.headers['Force-headers'] = '1';
});
req.send(function (err, data) {
if (err) {
console.log(err, err.stack);
context.fail('Internal Error: The email could not be sent.');
} else {
console.log(message);
console.log('The email was successfully sent')
context.succeed('The email was successfully sent');
}
});
});
};
if you have and any query regarding mailcomposer then check [here][1] this link below
[1]: https://nodemailer.com/extras/mailcomposer/

Nodemailer - email send but not receive

I'm build an API with feathersjs and I need to send an email with an attachment.
The email seems to be send but I receive nothing.
In my mail.service.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'smtp.office365.com',
port: 587,
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'gil.felot#myaccount.com',
pass: 'MyPassWord'
}
});
// Check the connection to the service.
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
Then in my hook
hook => {
const file = hook.params.file;
const email = {
from: 'gil.felot#myaccount.com', // sender address
to: 'mygmailaccount#gmail.com', // list of receivers
subject: 'Test Nodemailer', // Subject line
// text: req.body.text, // plaintext body
html: '<b>Hello world 🐴</b>', // html body
attachments: [
{
filename: file.originalname,
contents: new Buffer(file.buffer, 'base64'),
encoding: 'base64'
}
]
};
return hook.app.service('mail').create(email)
.then(function (result) {
console.log('Sent email', result);
}).catch(err => {
console.log(err);
});
}
then I got
Server is ready to take our messages
Sent email
Object {from: "gil.felot#myaccount.com", to: "mygmailaccount#gmail.com", subject: "Test Nodemailer", html: "Hello world 🐴"}
I have no idea how to check where the problem come from.
I was missing the from part while creating a mail while I was able to send mail via google smtp but my own smtp was failing with the above configuration
Was working with google
var mailOptions = { to: email, subject: 'Forgot Password', html: mailData };
Working with my smtp as well:
var mailOptions = { from: 'serverName.com', to: email, subject: 'Forgot Password', html: mailData };
Consider adding name while defining nodemailer configuration as well
let transporter = nodemailer.createTransport({
name: 'example.com' // <= Add this
host: 'smtp.example.email',
port: 587,
Ok I figure it out !
I needed to add the transporter.sendMail() inside the mail.class.js to trigger this action when I call hook.app.service('mail').create(email)
Working and the attachement file that is 0 byte in the mail but the good size inside my variable.
For me this was what I realized; if the html does not have the html tags, then the email is not sent. i.e.
This template will work
<html>
<body>
Hello and welcome
</body>
</html>
This template will not work:
<body>
Hello and welcome
</body>
This is especially when sending to office365, refer to this other question here:
Nodemailer doesn't send emails to outlook.office365 accounts

Change the design of email body

I have written the code for sending email in email.js as follows:
Accounts.emailTemplates.siteName = "xyz";
Accounts.emailTemplates.from = "xyz <admin#xyz.com>";
Accounts.emailTemplates.verifyEmail = {
subject() {
return "[xyz] Verify Your Email Address";
}
};
Accounts.emailTemplates.verifyEmail.text = function( user, url) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace( '', '' ),
supportEmail = "support#xyz.com",
emailBody = `To verify your email address (${emailAddress}) visit the following link:\n\n${urlWithoutHash}\n\n If you did not request this verification, please ignore this email. If you feel something is wrong, please contact our support team: ${supportEmail}.`;
return emailBody;
}
The email is working and all I want is to change the Design. How to design the email body? Can I insert the html code inside the email body so that I can have a proper responsive email design? I have tried in many ways. Can anyone please help me out?
I have used mail gun API for sending emails is there anyway to use template.
I have tried with grunt email template and am struck with that I need help to get complete my task.
You can create an email template using SSR package.
Accounts.emailTemplates.verifyEmail.html = function (user, url) {
SSR.compileTemplate( 'registartionEmail', Assets.getText( 'email_templates/registration_confirm.html' ) );
var emailData = {
x: y;
};
return SSR.render( 'registartionEmail', emailData );
};
To handle the process of converting templates into raw HTML on the server, you need to add a package to your application called meteorhacks:ssr. Once you have the package installed, you can store plain HTML files inside your /private directory and then convert them later, passing any data to replace handlebars helpers like {{name}} in the process.
For example, here is some code I have used to send a welcome email when new users register:
import { SSR } from 'meteor/meteorhacks:ssr';
const getHTMLForEmail = (templateName, data) => {
SSR.compileTemplate(templateName, Assets.getText(`email/templates/${templateName}.html`));
return SSR.render(templateName, data);
};
const sendEmail = (emailAddress, html) => {
if (emailAddress.includes('#')) {
const emailData = {
to: emailAddress,
from: 'Test Email <hello#test.io>',
subject: 'Welcome aboard, team matey!',
html,
};
Meteor.defer(() => Email.send(emailData));
}
};
export const sendWelcomeEmail = (user, profile) => {
let email;
if (user.services.facebook) {
email = user.services.facebook.email;
} else if (user.services.google) {
email = user.services.google.email;
}
const data = {
email,
name: profile && profile.name ? profile.name : '',
url: 'www.google.com',
};
const html = getHTMLForEmail( 'welcome-email', data );
sendEmail(data.email, html);
};
You will find the following two articles from Meteor Chef very useful (also shows how the html email template looks like):
Using the email package
Sign up with email verification

Getting error sending email in nodejs with emailjs

[error: can't set headers after they are sent.]
createCredentials() is deprecated, use tls.createSecureContext instead
{[Error: bad response on command '-']
code:2
smtp : '550 5.3.4 Requested action not token; To continue sending messages,
please sign in to your account.\n}
I have been trying to send email in nodejs with emailjs and nodemailer but i keep on getting the error above.
transportEmail: email.server.connect({
user: "ghConnectUs#outlook.com",
password:"******",
host: "smtp-mail.outlook.com",
tls: {ciphers: "SSLv3"}
})
note: i have include all modules.
i'm hoping somebody can point me to the right path. i just want to send me using outlook or gmail in node app.
Below is the code for sending email from nodejs app (through Gmail):
Using Nodemailer v1.3.4:
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "email_id_of_gmail_account",
pass: "password_of_gmail_account"
}
});
var mailOptions = {
from: 'sender_email_id', // sender address
to: 'receiver_email_id, some_other_email_if_requierd', // list of receivers
cc: 'cc_email_id'
subject: 'subject text', // Subject line
text: 'body plain text', // plaintext body
html: '<b>body html</b>' // html body
};
var sendEMail = function () {
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log('Message sent: ' + info.response);
}
});
};
sendEmail();
Note: if you are using Nodemailer version 0.7 or lower, then transporter object will created like this:
var transporter = nodemailer.createTransport('SMTP', {
service: "Gmail",
auth: {
user: "email_id_of_gmail_account",
pass: "password_of_gmail_account"
}
});
Using emailJs v0.3.16:
var email = require("/node_modules/emailjs/email.js");
var server = email.server.connect({
user: "emailId_of_gmail_account",
password: "password_of_gmail_account",
host: "smtp.gmail.com",
ssl: true // in case outlook, use "tls: {ciphers: "SSLv3"}"
});
var message = {
text: "body text",
from: "senderName <sender's_email_id>",
to: "receiverName <receiver_email_id>",
subject: "subject text",
attachment: // optional
[
{data: "<html>i <i>hope</i> this works! html </html>", alternative: true},
{path: "path/to/file.zip", type:"application/zip", name:"renamed.zip"}
]
};
var sendEMail = function () {
server.send(message, function (err, message) {
console.log(err || message);
});
};
sendEmail();