Triggered Emails to Contacts (2020)


Our block of code (referenced below) is returning a " contactId does not match current session contact" and emails are not sent to the inputed emails on our live Wix site. The only way we have been able to make this code work is by clearing cache ahead of inputing emails on the live site, which is impractical in a real life scenario as users will not know that there is a bug and suggests that the identity of the current user is the root of the problem. Ideally, an email should be sent to the inputed email on every button action regardless of the current user’s identity and even on repeat actions (e.g. if an email is sent to a user’s email input and the user proceeds to repeat the same action with a different or identical email there should be two emails sent every time)

We would like to send emails through Wix without using a 3rd party option given the provided Wix APIs. Wix automations will not work in our case as there are instances where we would like to send two emails simultaneously and we are not collecting data through forms. Could you please recommend a block of code that will successfully send triggered emails using the required Wix API given the inputs in the code below. We are sure there are a multitude of Wix sites that are accomplishing this.

Active Inputs (seen below)
input1 = user’s inputed email
join_waitlist_click = button action
welcome_email = triggered email format

Inactive Inputs
general_waitlist = database
inputed_email = email database field
*provided if needed in recommended code

Current Syntax

import wixCRM from 'wix-crm';

$w.onReady(function () {
    console.log("made it to onReady")
});

export function join_waitlist_click(event) {
    console.log("made it to join_waitlist_click")
    wixCRM.createContact({
    "emails": [$w("#input1").value],
    })
    .then((contactId) => {
    console.log(contactId)
    wixCRM.emailContact('welcome_email', contactId);
    })
    .then(() => {
    console.log('email sent')
    })
    .catch((err) => {
    console.log(err);
    });
}

#triggeredemails #WixAPIs

Would really appreciate some help on the above: @givemeawhisky @yisrael-wix @jonatandor35 @giri-zano @skmedia @yoav-wix

I do not use wix-CRM myself, nor Triggered emails. I use my own contact collection and send emails thru a third party (which could even be gmail, direct, without having to go thru an extra layer like emailjs).

Thanks for the response, Giri. We have read your " Send email thru Gmail and others in Wix Code " post, but we are trying to make this work solely through Wix w/o using a 3rd party.

Firstly, remember that o nce you create a contact, you can’t then create another contact again with the same email.

If you tried that no email would be triggered as it t works once for each contact created only.

I would go back and recheck your code with the provided sample here.
https://www.wix.com/corvid/reference/wix-crm.html#emailContact
https://support.wix.com/en/article/corvid-tutorial-sending-a-triggered-email-to-contacts

Create a contact and then send a Triggered Email to the new contact

import wixCrm from 'wix-crm';

$w.onReady(function () {
  $w("#myButton").onClick( () => {
    wixCrm.createContact( {
      "firstName": $w("#firstName").value,
      "lastName": $w("#lastName").value,
      "emails": [$w("#email").value],
      "phones": [$w("#phone").value]
    } )
    .then( (contactId) => {
      wixCrm.emailContact("thankyou", contactId, {
        "variables": {
          "firstName": $w("#firstName").value,
          "lastName": $w("#lastName").value
        }
      } );
    } );
  } );
} );

You have it wrong on your emailContact code on line 14.

With you changing the click event from the code itself to adding it through the properties panel, it should look like this.

import wixCRM from 'wix-crm';

$w.onReady(function () {
});

export function myButton_click(event) {
 wixCRM.createContact({
   "emails": [$w("#email").value]
  })
  .then((contactId) => {
   wixCRM.emailContact("triggeremail", contactId, {
    })
    .then(() => {
     // do something after the email was sent
    })
    .catch((err) => {
     // handle the error if the email wasn't sent
    });
  });
}

You can do it with a from that saves the email to a dataset first with the use of onAfterSave in your code, something like this.

import wixCRM from 'wix-crm';

$w.onReady(function () {
  $w("#dataset1").onAfterSave(() => {
    let email = $w("#email").value;

wixCRM.createContact({ 
        "emails": [email]

      }) 
      .then((contactId) => { 
        return wixCRM.emailContact('triggeremail', contactId, { 
          "variables": { 
            "email": email
          } 
        });  
      }) 
      .catch((err) => { 
        // handle the error if the email wasn't sent
        console.log(`Error: ${err}`);
      }); 
  }); 
}); 

@givemeawhisky thanks for catching the line 14 nit; however, we are still running into the same " contactId does not match current session contact" issue.

A triggered email is successfully sent when a user initially visits the page and enters their email address because a “current session contact” is not logged yet.

A triggered email is unsuccessfully sent when a user repeats the process and attempts to enter a different email address because a “current session contact” is logged after the initial input.

Is there a way to prevent the page from collecting a “session contact” upon initial submission so a user can continuously submit inputs and triggered emails are sent every time? We are close just need a simple work around.

For context, this is important for our page as we first ask for an email to join a waitlist and proceed to ask the same user for recommendation emails (see below)

Note: we were able to confirm the “current session contact” issue because a triggered email is successfully sent every time if a user repeatedly inputs the same email address because the logged session contact matches the input.

Bump

Have you tried sending emails from the backend instead of frontend with wix-crm-backend? You could give it a try with a small test function. Think the session problem would not exist there. But again, no expert on matter.

@giri-zano haven’t tried pairing any backend code yet, but will test out. Have you seen any references to backend syntax or previous forum posts that have examples of how to set up a backend triggered email?

You won’t be able to avoid using any storage options here otherwise Wix will not be able to store the newly created contact Id in the browsers session storage for that current public user.

The only way around this is to close the browser and open up a new window again, so that you clear the session storage.

You can’t simply just use another email address or open another tab whilst you are still viewing the site as the user who inserted their email into the create contact function.

This is because the contact Id is still being used for that user and that user only whilst they are browsing the site.

As Giri has already mentioned about the Wix CRM Backend API, if you are wanting to send emails to contacts who are not currently viewing the site, you would need to make use of Wix CRM Backend API and use the email function from that instead.
https://www.wix.com/corvid/reference/wix-crm-backend.html#emailContact

You will need to take the email addresses that the current user adds for your free trial form and use those as the contactId for this to work for you.

@givemeawhisky sounds good, we are going to go ahead and use the WIX CRM Backend API and call it from the front end and see if we can bypass the session error. Will report back to the forum after implementing and testing.

@givemeawhisky @giri-zano It looks like everything is up and running correctly after adding backend functionality! In 1 of 2 instances in which the Free Trial prompt (referenced above) appears on our site, we were also able to send 2 emails simultaneously!

Troubleshoot: In the 2nd instance of the Free Trial prompt, our code is only successfully sending 1 email out of the 2 inputed. Believe the backend is running fine and this is a frontend issue with the onClick event handler we are running seeing that the same button triggers two code paras. Let us know if you have any suggestions on how to fix the code HIGHLIGHTED IN BLUE in the frontend below as that is the email input that is not being sent.

Backend (Welcome, for Join Waitlist - view referenced above)

import wixCrmBackend from 'wix-crm-backend';

export function welcome_email_marketing(user_email2) {
 return wixCrmBackend.createContact({
 "emails": [user_email2],
        })
        .then((contactID) => {
            wixCrmBackend.emailContact("welcome_email", contactID)
                .then(() => {
                    console.log("email sent")
                })
                .catch((err) => {
                    console.log(err)
                });
        });
}

Backend (Invite, for Free Trial - view referenced above)

import wixCrmBackend from 'wix-crm-backend';

export function invite_email_marketing(user_email1) {
 return wixCrmBackend.createContact({
 "emails": [user_email1],
        })
        .then((contactID) => {
            wixCrmBackend.emailContact("invite_email", contactID)
                .then(() => {
                    console.log("email sent")
                })
                .catch((err) => {
                    console.log(err)
                });
        });
}

Frontend

import { welcome_email_marketing } from 'backend/welcome_email_marketing';
import { invite_email_marketing } from 'backend/invite_email_marketing';

$w.onReady(function () {

    $w("#button39").onClick((event) => {
 let email1 = $w("#input30").value;
        welcome_email_marketing(email1)
    });

    $w("#button16").onClick((event) => {
 let email2 = $w("#input21").value;
        invite_email_marketing(email2)
    })

    $w("#button16").onClick((event) => {
 let email3 = $w("#input22").value;
        invite_email_marketing(email3)
    })

})

Thanks in advance!

I don´t understand why you use all those buttons and duplicate pieces of code. Why not this:
a) collect 3 email addresses at the frontend
b) put them into an array and call a backend fucntion with the array as an argument
c) at backend, a for-loop for the length of the array, creating contact per cycle, send email, next one, done. This way only 1 piece of code.
You might want to put a timeout in the backend (start with 1 sec, see how that works) after every email, so you give the CRM mail function some time to not choke: it is not made for bulk emailing and I have encountered this many times in other solutions.

@user1546 @givemeawhisky Just wanted to check and see if either of you ever ended up getting this to work? I am trying to do the same thing but with variables in the front end. The front end works great and triggers the email with the variables, but I want to send an email to a contact I set from the backend at the same time so the site owner can get a copy of the email. Cannot seem to figure this out.

You can see my code here: https://www.wix.com/velo/forum/velo-pro-discussion/triggered-email-issue-for-custom-price-quote-form