Send mail by retrieving contact ID

Hello everyone,

I’m sorry, but I come back again with my previous pb (Thanks to noahlovell and Pratham, and sorry if i open a new ticket. : it still doesn’t work.

Let me explain : the Customers can not log in the site : no subscription possible : they don’t have accounts: Only 2 or three persons can log in (2 employees and myself).

Customers make a reservation from a form on a page (without even registering), and after that I receive a notification of this reservation. So i log in as admin in the “back office” that I created, and I validate their reservation. At this point, an email must be sent to the customer to confirm his reservation (this email is in a field of the form that I validate).

However, the problem: it is me who receives the confirmation email, because it is me who is connected, and not the customer. I would like it to be sent to the customer who has sent the reservation, by retrieving maybe his ID or something else?

Question : is it possible to retrieve the ID of the client by a code (not a member, just a contact), and then i will try with a code to send the mail to this ID.

I’ve got this error the the google console : 109 Error: contactId does not match current session contact (401)
I know how to do for a member but with a simple contact?

Thank you very much for your help…

**Product:**Wix Editor

As long as the user is not registered in your LOGIN-SYSTEM/CONTACTS he won’t have an ID. So the following is logical →

I’ve got this error the the google console : 109 Error: contactId does not match current session contact (401)

→ Customers submit a form without logging in (they’re not site members yet)

What could be possible?

Use an external email service (like SendGrid, Mailchimp Transactional, or EmailJS) via backend code, pulling the customer’s email address directly from the form submission.

Try Email-JS, should be simple. Sendgrid also a possible solution.

You grab the email of the user either directly from the input-field…
const customerEmail = $w(“#emailInput”).value; or from cms later.

Then you generate something similar like —>

// backend/sendEmail.jsw
import { fetch } from 'wix-fetch';

export function sendConfirmationEmail(to, subject, body) {
  const apiKey = "YOUR_SENDGRID_API_KEY";

  return fetch("https://api.sendgrid.com/v3/mail/send", {
    method: "post",
    headers: {
      "Authorization": `Bearer ${apiKey}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      personalizations: [{ to: [{ email: to }] }],
      from: { email: "your@email.com", name: "Your Restaurant" },
      subject: subject,
      content: [{ type: "text/plain", value: body }]
    })
  }).then(response => response.json());
}

…and …

import { sendConfirmationEmail } from 'backend/sendEmail';

$w.onReady(() => {
  // assuming you validate the reservation here
  const customerEmail = item.email; // retrieved from the collection
  const subject = "Reservation Confirmed";
  const message = `Hi ${item.name}, your reservation has been confirmed!`;

  sendConfirmationEmail(customerEmail, subject, message)
    .then(() => console.log("Email sent"))
    .catch(err => console.error("Email failed", err));
});

Those are just examples, you will have to modify and to edit those, for example using the newer wix architecture for backend-coding…

webMethod( )


Defines a backend function that can be called from the frontend.

The webMethod() function is a wrapper used to export functions from backend code that can be called from the frontend.

The permissions parameter is used to define the permissions needed to call the function in frontend code. Import the Permissions enum from the wix-web-module module to define the permissions. The permission options are:

  • Permissions.Anyone: Any site visitor can call the function.
  • Permissions.Admin: Only site admins can call the function.
  • Permissions.SiteMember: Only site members can call the function.

The cache object, found in the options parameter, allows you to cache or temporarily store the return value of web methods. Use the ttl property to define the duration, in seconds, for which you want the return value to be cached. If the Time To Live (TTL) is not set, the default value is 604800 seconds, which is approximately 1 week.

Assign identifiers to caches using the tags property of the cache object. Tags enable you to specify cached return values that may require invalidation due to significant changes in your data. To invalidate web method caches, use the invalidateCache() function from wix-cache-backend. Once invalidated, the return value is re-cached the next time your backend function is called. Learn more about web method caching.

Important:

  • The tags property is required for caching. Without tags, nothing is cached.
  • The invalidateCache() method from wix-cache-backend is currently in developer preview.

Web methods must be defined in files with a .web.js extension and so on and so on…

Well sorry!!!

But seems wix blocks my reply…

Hello,

Our automated spam filter, has temporarily hidden your post in Send mail by retrieving contact ID for review.

A staff member will review your post soon, and it should appear shortly.

We apologize for the inconvenience.

We will wait for clarification…

In short —>

Use an external email service (like SendGrid, Mailchimp Transactional, or EmailJS) via backend code, pulling the customer’s email address directly from the form submission.

We have some automated tools that help us moderate the forum - sometimes they get things wrong. Just reviewed and approved :flexed_biceps:

1 Like

Hi KEYBOARD-WARRIOR

Thank you for your answer.
Effectively i would like to use BREVO (Not sendgrid)

What about :

return fetch(“https://api.sendgrid.com/v3/mail/send”, {
method: “post”,
headers: {
“Authorization”: Bearer ${apiKey},
“Content-Type”: “application/json”
},

Yes I just set this up on my site. You have to use an external email service provider. I used Sendgrid.

I did have to use code from ChatGPT, but I got it working within 30 min. How it works → Email addresses (sellers) are stored in CMS Database from a form that’s filled out → Customer fills out form on a particular dynamic page, by which the particular email address for that particular seller is pulled dynamically. Backend code and frontend code then hook that message up with the email address and send via Sendgrid.

ChatGPT allowed me to do this. Otherwise, I would be hiring someone. Ask it questions, it will run you through how to build a spacecraft and fly to Mars.

Hello

I created my BACKEND: called email.web.js

import { fetch } from ‘wix-fetch’;

export function sendEmail(to, nomClient) {
const apiKey = “XXXXXXXXXXXX”; // À remplacer par ma vraie clé
const fromEmail = “XXXXXXXXXX”; // remplacer par mon Adresse validée sur Brevo
const fromName = "XXXXXXXXXXX;

const body = {
    sender: { name: fromName, email: fromEmail },
    to: [{ email: to }],
    subject: "Votre facture",
    htmlContent: `
        <p>Bonjour <strong>${nomClient}</strong>,</p>
        <p>Veuillez trouver ci-joint votre facture.</p>
        <p>Cordialement,<br>L'équipe ${fromName}</p>
};

return fetch("https://api.brevo.com/v3/smtp/email", {
    method: "POST",
    headers: {
        "api-key": apiKey,
        "Content-Type": "application/json",
        "Accept": "application/json"
    },
    body: JSON.stringify(body)
})
.then(response => {
    if (!response.ok) {
        throw new Error("Erreur d'envoi d'email : " + response.statusText);
    }
    return response.json();
});

}

AND BELOW MY FRONTEND:

import { sendEmail} from ‘backend/email.web’;

$w.onReady(function () {

$w('#sendMailButton').onClick(() => {
    const email = $w('#MailClient').value;
    const nomClient = $w('#NomClient').value;

    if (!email || !nomClient) {
        console.warn("Veuillez remplir tous les champs.");
        return;
    }

    sendEmailBrevo(email, nomClient)
        .then(() => {
            console.log("Email envoyé avec succès !");
        })
        .catch((err) => {
            console.error("Erreur lors de l'envoi de l'email :", err);
        });
});

but there is an error:

Everything seems now to be OK… The name of my function had an error.
I test it and comme back to you

thank you

1 Like