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

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/

Related

How to send pdf file as an attachment in sendgrid node.js v3 client

I am using v3 node.js client to send an email. Now , I want to send pdf attachment with the email. I went through the API documentation. But I did not find anywhere how to do it.
I am using the following code to send an email.
const msg = {
to: process.env.EMAIL_ID,
from: process.env.ALERT_EMAIL_ID,
subject: subjectText,
text: info
};
sgMail.send(msg);
Let us assume your PDF is in S3.
Get your file from S3
const pdfFile = await s3
.getObject({
Bucket: PDF_BUCKET_NAME,
Key: `flight-${fileName}.pdf`,
})
.promise();
Once you have the file
const base64data = pdfFile.Body.toString('base64');
const data = {
from: 'text#example.in',
to: user.emailId,
subject: 'Your ticket for flight PNR XYSSA1 from DEL-BLR',
html: `Please find attached your ticket
<br><br>Regards<br>
Team Example`,
attachments: [
{ content: base64data, filename: 'flight-ticket', type: 'application/pdf', disposition: 'attachment' },
],
};
await sgMail.send(data);
In case you have your file in the filesystem, just get the buffer from fs.readFile convert it into base64 like shown above and repeat the steps and you should be good to go.

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

node.js send email successful, but mail not found

I am using https://github.com/eleith/emailjs for my node.js application
After setting up the configuration properly, when I send email, I get the successful message in my log, but I do not see any mails either in the inbox or spambox :-(..
I using gmail, smtp.gmail.com, ssl:true, port:465.
email.send({...},function(err, message) {
if (err) {
console.log('Error sending email : ', err);
}
else {
console.log('Email SUCCESSFULLY sent', message);
}
^[[32m[2011-10-13 06:53:28.758] [INFO] console - ^[[39mEmail SUCCESSFULLY sent {
attachments: [],
html: null,
header:
{ 'message-id': '<1318488805460.5532#Abcd-PC>',
from: 'xxxxx#gmail.com',
to: 'yyyyy#gmail.com, ',
cc: 'zzzzz#gmail.com',
subject: 'Test mail from emailjs' },
content: 'text/plain; charset=utf-8',
text: 'Testing sending email' }
I use the following code for my emails in node.js (using emailjs)
var server = email.server.connect({
user: 'your#gmail.com',
password: 'gmailPass',
host: 'smtp.gmail.com',
ssl: true
});
server.send({
text: 'hello world',
from: 'obama#state.gov',
to: 'someone#else.com',
subject: 'just a subject here'
}, function(err, message) {
if (err) {
// err
} else {
// ok
}
});
Problem was comma(,) "yyyyy#gmail.com," in the 'to' email. I was trying to add multiple ids separated by commas(,) and that created the problem..
In the documentation, they have mentioned though
**"someone <someone#gmail.com>, another <another#gmail.com>"**
may be it expects the email format to be in the form they mentioned.