0

I don't know which encoding to do while sending email attachment from postmark attachments feature in the Content field.

I have already tried the following method to convert the pdf file to base64 but not find working:

fs.readFileSync("./filename.pdf").toString('base64')
////////
pdf2base64("./filename.pdf").then(
        (response) => {
            base= response //cGF0aC90by9maWxlLmpwZw==
        }
    ).catch(
        (error) => {
            console.log(error); //Exepection error....
        }
    )
/////
 function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer.from(bitmap.toString('utf-8'),'base64');
}

The code from which I am trying to send email is below:

var client = new postmark.ServerClient("*****");
  client.sendEmail({
    "From": "example@abc.com",
    "To": "abc@abc.com",
    "Subject": "Test",
    "TextBody": "please find attached file of your agreement",
    "Attachments": [
      {
        "Name":  'index.pdf',        
     "Content":fs.readFileSync("./filename.pdf").toString('base64'),
       "ContentType": "application/pdf"
      }
    ]
  }).then((result) => {
    console.log("the result is :", result)
  }).catch((err) => {
    console.log("error is : ", err)
  });

All I want it to find the method of how to encode as per the requirement for this email attachment. What should I put in the content field to send the errorless file

Jawwad Turabi
  • 322
  • 4
  • 12

2 Answers2

1

Can you reach out to our support team about this? They'll definitely be able to help. https://postmarkapp.com/contact

0

First you have to convert your file in Base64 string.

For this, you can use the following function.

const blobToBase64 = blob => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        return new Promise(resolve => {
          reader.onloadend = () => {
            resolve(reader.result);
          };
        });
      };

After blob/file converting to Base64 string, you have remove the following substring from Base64 string.

data:application/pdf;base64

You can do it by following code:

        const updatedBase64String = res.replace("data:application/pdf;base64,", "")

Now you can use the string in your content.

The complete code for you would like as

const blobToBase64 = blob => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise(resolve => {
      reader.onloadend = () => {
        resolve(reader.result);
      };
    });
  };
  
   blobToBase64(pdfConvertedToBlob).then(res => {
       const updatedBase64String =  res.replace("data:application/pdf;base64,", "")
          
       client.sendEmail({
          "From": "example@abc.com",
          "To": "abc@abc.com",
          "Subject": "Test",
          "TextBody": "please find attached file of your agreement",
          "Attachments": [
              {
                  "Name":  'index.pdf',        
                  "Content": updatedBase64String,
                  "ContentType": "application/pdf"
              }
           ]
       }).then((result) => {
           console.log("the result is :", result)
       }).catch((err) => {
           console.log("error is : ", err)
       });
    }

One thing, to remember. First you have to convert your local PDF file to BLOB

For this, you have two choices. First get the file from API, and get it in BLOB format like as

axios({
    method: "post",
    url: deployedServer,
    data: data,
    headers: { "Content-Type": "application/json" },
    responseType: 'blob',
 })
  .then((pdfConvertedToBlob) => {
      // it is blob data
   });

Second you can convert it by input type file, and uploading local file there, and using it. You can use it as below.

<input type="file" id="files" name="files" />

// now js code

if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
 } else {
     alert('The File APIs are not fully supported in this browser.');
 }

 function handleFileSelect(evt) {
    let pdfConvertedToBlob = evt.target.files[0]; // FileList object

 }

Hope it will helpful to you.

vineet tanwar
  • 329
  • 2
  • 9