Search code examples
javascriptemailtypescriptcontent-management-systemstoryblok

How can I use the Storyblok Email Service in Javascript / Typescript?


I have included the storyblok object and the serializeArray function:

import { serializeArray } from '../utils';
import { storyblok } from '../shims/Storyblok';

Now i want to pass the form data to the sendEmail function. How does it work?

submit(event:Event) {
    event.preventDefault();
    let formData = serializeArray(<HTMLFormElement> this.$());

    // what to do here?

    storyblok.sendEmail(message,
        // success
        function(data:any) {
            console.log(data);
            console.log('success');
        },
        // error
        function(data:any) {
            console.log(data);
            console.log('error');
        }
    )
}

Solution

  • The Storyblok contact form API allows you to pass a parameter in the following format:

    var message = {};
    message['message[email]'] = 'Valid Email goes here'; // assign your email field here
    message['message[body]']  = 'This is my Message'; // assign your message field here
    

    Those 2 fields (email & body) are required - you can pass as many parameters as you want to the API.

    You can try your request directly using the following cURL request

    curl 'https://api.storyblok.com/v1/messages?token={{YOUR_TOKEN}}' 
    -H 'pragma: no-cache' 
    -H 'origin: {{YOUR_SPACE_DOMAIN}}' 
    -H 'accept-encoding: gzip, deflate, br' 
    -H 'x-requested-with: XMLHttpRequest' 
    -H 'accept-language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,hr;q=0.2,el;q=0.2,bg;q=0.2,sr;q=0.2,fr;q=0.2,sq;q=0.2' 
    -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' 
    -H 'content-type: application/x-www-form-urlencoded' 
    -H 'accept: */*' 
    -H 'cache-control: no-cache' 
    -H 'authority: api.storyblok.com' 
    -H 'referer: {{YOUR_SPACE_DOMAIN}}' --data 'message%5Bemail%5D=test%40test.test&message%5Bbody%5D=yourMessageGoesHere' --compressed