Search code examples
amazon-web-servicesgmailamazon-sesmime-message

AWS SES Raw Email is sending both html and plain text


I'm following this helpful article to send an attachment using AWS SES (raw email).

It is working! Just one problem...the email is delivering both the html and the plain text. The plain text is displayed just below the html.

If I don't include plain text, it goes into gmail spam.

Any suggestions on how to prevent the plain text from displaying below the html?

var mimemessage = require('mimemessage');

const sendAWSEmailWithAttachment = (emailDetails) => {

  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION
  })


  const ses = new AWS.SES({ apiVersion: "2010-12-01" });

  var mailContent = mimemessage.factory({contentType: 'multipart/mixed',body: []});
  mailContent.header('From', 'Ticketglen <[email protected]>');
  mailContent.header('To', emailDetails.emailAddress);
  mailContent.header('Subject', emailDetails.subject);

  var alternateEntity = mimemessage.factory({
    contentType: 'multipart/alternate',
    body: []
  });

  var htmlEntity = mimemessage.factory({
    contentType: 'text/html;charset=utf-8',
    body:  emailDetails.content
  });

  var plainEntity = mimemessage.factory({
    body: emailDetails.plainText
  });

  alternateEntity.body.push(htmlEntity);
  alternateEntity.body.push(plainEntity);


  mailContent.body.push(alternateEntity);

  var data = fs.readFileSync(emailDetails.pathToAttachment);
  var attachmentEntity = mimemessage.factory({
  contentType: 'text/plain',
  contentTransferEncoding: 'base64',
  body: data.toString('base64').replace(/([^\0]{76})/g, "$1\n")
  });
  attachmentEntity.header('Content-Disposition', `attachment ;filename=${emailDetails.fileName}`);

  mailContent.body.push(attachmentEntity);

  ses.sendRawEmail({
    RawMessage: { Data: mailContent.toString() }
  }, (err, sesdata, res) => {
  console.log('err', err)
  console.log('sesdata', sesdata)
  console.log('res', res)

  });

}

Solution

  • You just need to comment this sentence:

    //  alternateEntity.body.push(plainEntity);
    

    I tested with your code. I am getting correct emails delivered to my gmail inbox both the time, once with plain text after html text and also with just html text.

    Probably the reason why you notice that gmail sends it to SPAM has more to do with the Gmail settings on the receiving party side. It could be the rules defined by the receiver or their past behaviour in marking certain emails as not important or spam leads Gmail to recognise this email also as spam. Content (HTML & Plan TexT) of your email is getting filtered by the user specific settings and being sent to Spam. But this may not be same for all your email recipients.