Send mail with Sendgrid HTML templates after saving a form. Working!

Page Code:

import { sendTemplateEmail } from 'backend/email'; 

function sendHTMLmail_RequestReceived() { 
    const sender = "valid-sendgrid-account@yuuktiyoga.cl"; 
    const bcc = "fixed-reply-account@yuuktiyoga.cl"; 
    const recipient = $w("#iptEmail").value; 
    const subject = `Request of ${$w("#dropTipoCert").value} received`; 
    const name = $w('#iptNombres').value; 
    const lastname = $w('#iptApellidos').value; 
    const run = $w('#iptRUN').value; 
    const type = $w('#dropTipoCert').value; 
    const year = $w('#iptAnno').value; 
    const trim = $w('#iptTrimestre').value; 
    const reason = $w('#iptMotivo').value; 
    const f_solicitud = $w('#dateEmision').value.toLocaleDateString(); 
    const f_limite = fechaLimite.toLocaleDateString(); 
    
    const body = { 
        "personalizations": [{ 
            "to": [{ 
                "email": recipient
             }], 
             "bcc": [{ 
                "email": bcc 
             }], 
             "dynamic_template_data": { 
                 "subject": subject, 
                 "Nombres": name, 
                 "Apellidos": lastname, 
                 "Email": recipient, 
                 "RUN": run, 
                 "Tipo": type, 
                 "Anno": year, 
                 "Trimestre": trim, 
                 "Motivo": reason, 
                 "F_solicitud": f_solicitud, 
                 "F_entrega": f_limite, 
                 "Status": "Entered", 
                 "Sender_Name": "Formacion Yuukti Yoga", 
                 "Sender_Address": "Av Libertador Bernardo O'Higgins 2126", 
                 "Sender_City": "Santiago", 
                 "Sender_Country": "Chile" 
               }
         }], 
         "from": { 
               "email": sender 
         }, 
         "reply_to": { 
               "email": bcc 
         }, 
         "template_id": "d-4cdd70ceb22a4adfbadba17ccdf9d241"      // replace with your template_id 
    }; 
    
    sendTemplateEmail(body) 
        .then(response => console.log(response));
} 

// dataset.onSave 
export function dsCertificados_afterSave() { 
    sendHTMLmail_RequestReceived(); 
} 

// dataset.onError 
export function dsCertificados_error(operation, error) { 
    const errorOp = operation; // "save" 
    const errorMessage = error.message; 
    
    $w("#txtDSerror").text = errorMessage + '.\nError on ' + errorOp + " operation." 
}

backend/email.jsw

import { sendWithHTMLTemplate } from 'backend/sendGrid'; 

export function sendTemplateEmail(body) { 
    const key = "YOUR_SENDGRID_API_KEY_HERE"; 
    return sendWithHTMLTemplate(key, body); 
}

backend/sendGrid.js

import { fetch } from 'wix-fetch'; 

export function sendWithHTMLTemplate(key, body) { 
    const url = "https://api.sendgrid.com/v3/mail/send"; 
    const headers = { 
        "Authorization": "Bearer " + key, 
        "Content-Type": "application/json" 
    };
     
    return fetch(url, { 
             "method": "POST", 
             "headers": headers, 
             "body": JSON.stringify(body) 
         }) 
         .then(response => response.text); 
}

Hope this helps you!

1 Like

It just returns “undefined”

damn it

No has tenido problemas con sendgrid? A mi a veces me envĂ­a los correos, y otras veces no.

Si he tenido problemas, pero mas que Sendgrid pienso que es Wix que hace cambios y cosas dejan de funcionar (me pasĂł cuando actualizaron el renderizador y los QR ya no se veian, tuve que abrir caso y volver al renderizador antiguo).

Tengo 2 sitios usando este metodo y cuando fallo en uno, el otro seguia mandando bien los correos.

Vuelve a tu pĂĄgina donde se gatilla la funcion enviarCorreo y revisa en modo Vista previa algĂșn error en consola que antes no habia (el diseñador cambio algun elemento que referenciabas por ejemplo), si esta todo bien, graba y vuelve a publicarla. Esto me ha funcionado.

Otro problema tipico que tengo con Wix es tener que limpiar la cache del navegador despues de cada cierto tiempo, revisa eso tambien.

actually, I have this response: “undefined”
 please help us

Actually it isnt working. This is my work:

page code:
import { sendTemplateEmail } from ‘backend/emailpruebatemplate’ ;

function sendHTMLmail_RequestReceived ( ) {
const sender = “valid-sendgrid-account@yuuktiyoga.cl” ;
const bcc = “fixed-reply-account@yuuktiyoga.cl” ;
const recipient = $w ( “#emailInput” ). value ;
const subject = Request of ${ $w ( "#nameInput" ). value } received ;
const name = $w ( ‘#nameInput’ ). value ;

const  body  = {  
    "personalizations" : [{  
        "to" : [{  
            "email" :  recipient 
         }],  
         "bcc" : [{  
            "email" :  bcc  
         }],  
         "dynamic_template_data" : {  
             "subject" :  subject ,  
             "Nombres" :  name , 
           } 
     }],  
     "from" : {  
           "email" :  sender  
     },  
     "reply_to" : {  
           "email" :  bcc  
     },  
     "template_id" :  "d-7c1025a6c64b4b8989acb79c4e3db1ca"       // replace with your template_id  
};  

sendTemplateEmail ( body )  
    . then ( response  =>  console . log ( response )); 

}

/**

jsfile:
import { fetch } from ‘wix-fetch’ ;

export function sendWithHTMLTemplate ( key , body ) {
const url = “https://api.sendgrid.com/v3/mail/send” ;
const headers = {
“Authorization” : "Bearer " + key ,
“Content-Type” : “application/json”
};

**return**  fetch ( url , {  
         "method" :  "POST" ,  
         "headers" :  headers ,  
         "body" :  JSON . stringify ( body )  
     })  
     . then ( response  =>  response . text );  

}

jsw file:
import { sendWithHTMLTemplate } from ‘backend/sendGridpruebatemplate’ ;
import wixSecretsBackend from ‘wix-secrets-backend’ ;

export async function sendTemplateEmail ( body ) {
const sendGridSecret = JSON . parse ( await wixSecretsBackend . getSecret ( ‘sendGridSecret’ ));
const key = sendGridSecret . key ;
// const sender = sendGridSecret.senderEmail;
return sendWithHTMLTemplate ( key , body );
}