cs-icon.svg

Send Contentstack Content Over Email

Note: This guide lists the steps to send Contentstack content over an email when using Express.js web application framework. The steps may differ if you are using a different architecture.

In this guide, we will learn how to notify (and send content to) an email address whenever an event happens in Contentstack.

  1. Set up an app password using Gmail client
  2. Create content type to store outgoing email details
  3. Add application code to your Express web framework
  4. Set up webhook
  1. Set up an app password using Gmail client

    To send content from Contentstack over an email, you need to use an email client. You can use popular email clients such as Gmail or Mailchimp to send and receive content. This guide uses Gmail client to send Contentstack content over email. Gmail allows free user accounts to access email features and does not require recipients to accept incoming email requests.

    Note: The steps to set up your email client will differ as per the email client you use.

    To send content from Contentstack using Gmail, create an application-specific password to gain access to Gmail. Since Contentstack-powered applications work with Node.js, you can use the npm package manager to set up an app password. Use npm’s gmail-send module to send emails using Gmail.

  2. Create content type to store outgoing email details

    Contentstack can send data using webhooks whenever an event happens (learn more in Step 4). Webhooks can invoke a code that triggers an outgoing email (learn more in Step 3).

    You can set up a content type, the entry of which holds the details of your outgoing email (such as recipient email, title, body). Let’s learn how to do this.

    1. Create a content model named Email to specify the different ingredients of the email to be sent out when a webhook is triggered.
      Set Email as a single content type that can store just one entry.
    2. Add a Single Line Textbox field named Recipients.
      You can specify the different email IDs to which content needs to be sent in the “Recipients” field.
    3. Add a Single Text Box field named Subject to your content type.
      You can specify the subject of the email that you need to send out to the email recipients.
    4. Add a Rich Text Editor field named Email Body.
      You can specify the message you want to convey to the email recipients in the “Email Body” field.
    5. Create an entry for your “Email” content type and enter relevant content in all the available fields before saving or publishing it.Send_Contentstack_Content_Over_Email_1_highlighted.png
    6. Create a publishing environment where the entry needs to be published and give it a name of your choice.
      The most common environment names are staging, development, and production.
  3. Add application code to your Express web framework

    You need to define the code that will fetch content from Contentstack and send it over Gmail. This code retrieves field data from your “Email” content type and maps them to the ingredients of your email template.

    Add the following code to the webhook.js file present in the routes (user-defined folder containing JavaScript code) folder of your web application framework (Express):

    router.post("/mail", (req, res) => { //Express app code snippet
        let emailList = [];
        Stack.ContentType("email").Query() // pulling emails, subject, body from email content-type
            .toJSON()
            .find()
            .spread(function success(result) {
                result[0].email.split(",").map((str) => {
                    emailList.push(`${str}`);
                });
                var send = require("gmail-send")({ //using npm package https://www.npmjs.com/package/gmail-send
                    user: "email", //email to be sent from
                    pass: "app-specific-password", // Application-specific password
                    to: emailList,
                    subject: `${result[0].subject}`,
                    html: `
            ${result[0].email_body}
            
            ${req.body.data.entry} // JSON data from webhook
    `
                });
                send({}, function(error) {
                    logger.error(error);
                    res.status(200);
                    res.send("success");
                });
            });
    });
    

    The above code will fetch field data from the “Email” content type whenever the webhook is triggered. This field data includes the recipients for your email, the subject of your email, and the email body.

    Note: You can also use CSS styling in your HTML code to provide suitable formatting for the JSON content provided in the email.

  4. Set up webhook

    A simple way to get content out of Contentstack is to use our webhooks. You can think of webhooks as a trigger event for anything that happens in Contentstack. Here, create a webhook to trigger when any landing page is published on a specific environment.

    To create a webhook, log in to your Contentstack account and perform the following steps:

    1. Navigate to your stack and click on the “Settings” icon on the left navigation panel. 
    2. Select webhooks and then click on + New Webhook
    3. Provide a suitable name for your webhook.
    4. In the URL to notify section, specify the URL where your application is deployed. Append the name of the file where your application code is stored and the word “mail” to the URL to indicate a request to send a mail (e.g., http://www.example-site.com/{filename}/{action performed on webhook trigger}).
      This is the URL where Contentstack will post data when an event happens.
    5. Under the Conditional View section, select the options Any | Entry | Landing Pages | Published | {environment of your choice} | Successfully.Send_Contentstack_Content_Over_Email_2_highlighted.png
    6. Select the Enable Webhook checkbox and Save the webhook.

Now, whenever you publish an entry on the specified environment, a mail will be sent to the recipients declared in the field data of the Email content type. This mail will contain the entry data for the landing page that has been published on a specific environment. The entry data is sent in JSON format and can be formatted using CSS styling in your HTML code.

Additional Resources: You can refer to our guides on how you can use Contentstack Webhooks with AWS Lambda to automate several content management tasks.

Was this article helpful?
^