How do i send a file as attachment in a lambda function?

Just to clearify i’m not interested in using netlify form solution, i want to learn how to do this the manual way with lambda functions.

Currently when i send my form data to my serverless function i don’t recieve the files data (It’s getting send from client, not empty)

Console.log from serverless function:

{
  message: 'Test message',
  file: { '0': {}, '1': {} },
  name: 'Name',
  phone: 'Phone number exist, but not going to show ;)',
  email: 'example@email.com'
}

The files in the filelist are empty. I thought that maybe it was possible to encode the files to Base64 using fileReader, and then send the data. But it looks like the mail service that i’m using Mailgun doesn’t support Base64 string as attachments.

I’m not sure what else i can do, any help would be appreciated :slight_smile:

hey @HenrikDK, I am not a functions expert, but, I wonder if this might be helpful?

there may be an example in this repo that is what you are seeking:

Simples Solution is this:

// https://thecodebarbarian.com/sending-emails-using-the-mailgun-api.html

const mailgun = require('mailgun-js')

const mg = mailgun({apiKey: process.env.API_KEY, domain: process.env.DOMAIN, host: "api.eu.mailgun.net"});

const filename = 'test.txt';
const text = "Example test content."
const attch = new mg.Attachment({data: Buffer.from(text), filename: filename})

const data = {
  from: process.env.FROM,
  to: process.env.TO,
  subject: 'Hello',
  text: 'Testing Mailgun attachments.',
  attachment: attch
};

mg.messages().send(data, (error, body) => {
  console.log(body);
});

Or use Nodemailer Composer in the function for attachment.

// See: https://documentation.mailgun.com/en/latest/api-sending.html#examples
// See: http://nodemailer.com/extras/mailcomposer/#attachments

const path = require('path');
const mailgun = require('mailgun-js')
const MailComposer = require('nodemailer/lib/mail-composer');

const mg = mailgun({apiKey: process.env.API_KEY, domain: process.env.DOMAIN, host: "api.eu.mailgun.net"});

const mailOptions = {
  from: process.env.FROM,
  subject: 'Hello',
  text: 'Testing Mailgun attachments.',
  attachments: [
    { // utf-8 string as an attachment
      filename: 'text.txt',
      content: 'For testing just a text file. This could be a ReadStream, Buffer or other.'
    }
  ]
};

const mail = new MailComposer(mailOptions);

mail.compile().build(function(mailBuildError, message) {

  var dataToSend = {
    to: process.env.TO,
    message: message.toString('ascii')
  };

  mg.messages().sendMime(dataToSend, function(sendError, body) {
    if (sendError) {
      console.log(sendError);
      return;
    }
  });
});