File attachment using Sendgrid API

I having an issue while sending a file attachment with an email and the issue is when I am sending the file as an attachment with email but when opening the file in my email it’s showing me there is an error with file content and here the snippets of code.
here is the backend code

import {fetch} from ‘wix-fetch’;
export function sendWithService(key, sender, recipient,format,file) {
const url = “https://api.sendgrid.com/api/mail.send.json”;
const headers = {
“Authorization”: "Bearer " + key,
“Content-Type”: “application/x-www-form-urlencoded”
};
const data = from =${sender}&to=${recipient}&subject=${"Testing"}&text=${"Thanks you so much sir for your response"}&files[file]=<@file>;
const request = {
“method”: “post”,
“headers”: headers,
“body”: data
};
return fetch(url, request)
.then(response => response.json());
}
here is the frontend code where I am passing the file that have to be sent as an attachment after user upload the file and click on button to upload the file.

import {sendEmail} from ‘backend/email’;
$w.onReady( function () {
});
export function button1_click(event) {
$w(‘#dataset1’).save().then((item)=>{
let ext=getFileExtension3(item.file);
sendEmail(ext,item.file).then((response)=>{
console.log(response.message)
})
})
}
function getFileExtension3(filename) {
return filename.slice((filename.lastIndexOf(“.”) - 1 >>> 0) + 2);
}

Please kindly help me regarding this problem otherwise my contract got terminated with my client.

Have you gone through SendGrid’s own API documentation?
https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
Attachments - An array of objects in which you can specify any attachments you want to include.

See more about using SendGrid NodeJS here.
https://github.com/sendgrid/sendgrid-nodejs

Also see SendGrid’s own PHP samples here.
https://github.com/sendgrid/sendgrid-php/blob/master/USE_CASES.md#attachments

https://stackoverflow.com/questions/38599079/sendgrid-emailing-api-send-email-attachment

Use the SendGrid NPM (@sendgrid/mail)

NOTE: This will only work on “js” files, if you are on a “jsw” file then you need to move the **encoder** function to a “js” file.

import {fetch} from 'wix-fetch';
import sgMail from '@sendgrid/mail';

var api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXx';

export function bufferEncode(url) {
    createBuffer(url)
    .then( (buf) => {
        sendEmail(buf);
    });
}

const createBuffer = (url) => {
      return fetch(url, {
            method: 'GET',
            encoding: null
     })
     .then( (res) => {
         return res.buffer();
     });
}

const sendEmail = async(buffer) => {
 let encoded = await encoder(buffer);
 await sgMail.setApiKey(api_key);
 const msg = {
        to: 'email@domain.com',
        from: 'no-reply@domain.com',
        subject: 'Your attachment!',
        html: `<p>Hi!<br>
        <br>
        Thanks</p>`,
        attachments: [{
            content: encoded,
            filename: 'Attachment Name.png',
            type: 'plain/text',
            disposition: 'attachment',
            contentId: 'mytext'
       }]
 };
    sgMail.send(msg).then( function (err, response) {
         if(err){
             Promise.resolve(console.log(err));
         }else{
             Promise.resolve(console.log(response));
         }
     })
     .catch( (err) => {
         Promise.resolve(console.log(err));
     });
}

const encoder = (string) => {
     var encryptedBytes = Buffer.from(string);
     var encoded = encryptedBytes.toString('base64');
     return encoded;
}

To learn how to get an entire url of a image/document stored on Wix, search the forum. Tiaan has posted an example here.

Thank you so much brother let me check this if there would be anything then I will ask with you :slight_smile:

@shan It’s showing me an error.
When I am passing file url from page

Hi Shan,

Thanks for directing me here from the other form.
Taking a look at the above, which backend file do you suggest placing your code in? I’ve tried all three of my “sendGrid”, “email”, and “data” backends and I receive several errors stating it’s unable to load the @sendgrid/mail and base 64 encode modules. Is there another backend file we should create before calling them functions we’re importing?

Many thanks!

You need to install the NPM packages I have mentioned in my answer

https://www.wix.com/corvid/feature/npm-packages

Awesome, thank you so much for clarifying.

Used the following in my front end code to grab the URL, which worked:

const convertRegex = new RegExp(/wix:document:\/\/v1\/([^\/]+)\/(.*)$/); 
const item =$w("#dataset1").getCurrentItem(); 
const matches = item.file.match(convertRegex); 
const url = `https://static.wixstatic.com/ugd/${matches[1]}`;

which originated here: https://www.wix.com/corvid/forum/community-discussion/include-images-documents-in-form-submission-email

Happy to help. Thanks for sharing the solution for the image URL.