Coder Social home page Coder Social logo

alexzaganelli / strapi-plugin-email-designer Goto Github PK

View Code? Open in Web Editor NEW
320.0 4.0 47.0 1.81 MB

Design your own email templates w/ visual composer directly inside the Strapi admin panel and send composed emails programmatically from your controllers / services.

License: MIT License

JavaScript 100.00%
strapi email templates-design

strapi-plugin-email-designer's Introduction

Strapi Email Designer plugin ๐Ÿ’…

NPM Version Monthly download on NPM code style: prettier PRs welcome! License Follow Alex Zaganelli Repo stars Contributors

Design your own email templates directly from the Strapi CMS admin panel and use the magic to send programmatically email from your controllers / services.

Designer screenshot

Visual composer provided by Unlayer

ย 

โš™๏ธ Versions

  • Strapi v4 - (current) - v2.x
  • Strapi v3 - v1.x

ย 

โณ Installation

Install Strapi with this Quickstart command to create a Strapi project instantly:

# with yarn
yarn create strapi-app my-project --quickstart

# with npm/npx
npx create-strapi-app my-project --quickstart

This command generates a brand new project with the default features (authentication, permissions, content management, content type builder & file upload). The Quickstart command installs Strapi using a SQLite database which is used for prototyping in development.

yarn add strapi-plugin-email-designer@latest

# or

npm i -S strapi-plugin-email-designer@latest
  • you may need also to add to the unlayer domain to the Content Security Policy. Update the config file config/middlewares.js as:
// ...
- "strapi::security",
+ {
+     name: "strapi::security",
+     config: {
+       contentSecurityPolicy: {
+         directives: {
+           "script-src": ["'self'", "editor.unlayer.com"],
+           "frame-src": ["'self'", "editor.unlayer.com"],
+           "img-src": [
+             "'self'",
+             "data:",
+             "cdn.jsdelivr.net",
+             "strapi.io",
+             "s3.amazonaws.com",
+           ],
+         },
+       },
+     },
+   },
// ...
  • After successful installation you've to build a fresh package that includes plugin UI. To archive that simply use:
yarn build && yarn develop

# or

npm run build && npm run develop
  • or just run Strapi in the development mode with --watch-admin option:
yarn develop --watch-admin

#or

npm run develop --watch-admin

The Email Designer plugin should appear in the Plugins section of Strapi sidebar after you run app again.

๐Ÿ’„ Usage

  1. Design your template with easy on the visual composer. For variables use {{mustache}} templating language with the double curly braces tags ( {{ and }} ). You can leave the text version blank to automatically generate a text version of your email from the HTML version.

Tips: in the template's body is possible to iterate array like this:

{{#order.products}}
    <li>{{name}}</li>
    <li>${{price}}</li>
{{/order.products}}
  1. Send email programmatically:
{
  // ...

  try {
    await strapi
      .plugin('email-designer')
      .service('email')
      .sendTemplatedEmail(
        {
          // required
          to: '[email protected]',

          // optional if /config/plugins.js -> email.settings.defaultFrom is set
          from: '[email protected]',

          // optional if /config/plugins.js -> email.settings.defaultReplyTo is set
          replyTo: '[email protected]',

          // optional array of files
          attachments: [],
        },
        {
          // required - Ref ID defined in the template designer (won't change on import)
          templateReferenceId: 9,

          // If provided here will override the template's subject.
          // Can include variables like `Thank you for your order {{= USER.firstName }}!`
          subject: `Thank you for your order`,
        },
        {
          // this object must include all variables you're using in your email template
          USER: {
            firstname: 'John',
            lastname: 'Doe',
          },
          order: {
            products: [
              { name: 'Article 1', price: 9.99 },
              { name: 'Article 2', price: 5.55 },
            ],
          },
          shippingCost: 5,
          total: 20.54,
        }
      );
  } catch (err) {
    strapi.log.debug('๐Ÿ“บ: ', err);
    return ctx.badRequest(null, err);
  }

  // ...
}

Enjoy ๐ŸŽ‰

๐Ÿ– Requirements

Complete installation requirements are exact same as for Strapi itself and can be found in the documentation under Installation Requirements.

Supported Strapi versions:

  • Strapi v4.x.x

(This plugin may work with the older Strapi versions, but these are not tested nor officially supported at this time.)

Node / NPM versions:

  • NodeJS >= 14.21 < 19
  • NPM >= 7.x

We recommend always using the latest version of Strapi to start your new projects.

๐Ÿ”ง Configuration

You can pass configuration options directly to the editor that is used by this plugin. To do so, in your config/plugins.js file of your project, configure the plugin like this example:

module.exports = ({ env }) => ({
  // ...
  'email-designer': {
    enabled: true,

    // โฌ‡๏ธŽ Add the config property
    config: {
      editor: {
        // optional - if you have a premium unlayer account
        projectId: [UNLAYER_PROJECT_ID],

        tools: {
          heading: {
            properties: {
              text: {
                value: 'This is the new default text!',
              },
            },
          },
        },
        options: {
          features: {
            colorPicker: {
              presets: ['#D9E3F0', '#F47373', '#697689', '#37D67A'],
            },
          },
          fonts: {
            showDefaultFonts: false,
            /*
             * If you want use a custom font you need a premium unlayer account and pass a projectId number :-(
             */
            customFonts: [
              {
                label: 'Anton',
                value: "'Anton', sans-serif",
                url: 'https://fonts.googleapis.com/css?family=Anton',
              },
              {
                label: 'Lato',
                value: "'Lato', Tahoma, Verdana, sans-serif",
                url: 'https://fonts.googleapis.com/css?family=Lato',
              },
              // ...
            ],
          },
          mergeTags: [
            {
              name: 'Email',
              value: '{{ USER.username }}',
              sample: '[email protected]',
            },
            // ...
          ],
        },
        appearance: {
          theme: 'dark',
          panels: {
            tools: {
              dock: 'left',
            },
          },
        },
      },
    },
  },
  // ...
});

See Unlayer's documentation for more options.

๐Ÿšจ How to run the tests

Create the cypress.env.json file to the root and add your variables following this schema:

{
  "adminUrl": "http://localhost:1337/admin/auth/login",
  "user": {
    "email": "[email protected]",
    "password": "P1pp0#2021"
  }
}

Now let's install and open Cypress

# with yarn
yarn cypress:install
yarn cypress:open

# with npm
npm run cypress:install
npm run cypress:open

๐Ÿšง Roadmap

  • Template composer helper
  • Import design feature
  • Override Strapi's core email system feature
  • Preview email with real data feature
  • Tags feature
  • Custom components extension
  • Complete UI tests
  • i18n translations (help wanted!)

๐Ÿค Contributing

Feel free to fork and make a Pull Request to this plugin project. All the input is warmly welcome!

โญ๏ธ Show your support

Give a star if this project helped you.

๐Ÿ”— Links

๐ŸŒŽ Community support

๐Ÿ“ License

MIT License Copyright (c) 2020 Alex Zaganelli & Strapi Solutions.

Contributors โœจ

Thanks goes to these wonderful people (emoji key):

Alexandre Zaganelli
Alexandre Zaganelli

๐Ÿค” ๐Ÿ’ป ๐ŸŽจ ๐Ÿ›
Ron Chi
Ron Chi

๐Ÿ›
p_0g_8mm3_
p_0g_8mm3_

๐ŸŽจ ๐Ÿค”
Tobias Thiele
Tobias Thiele

๐Ÿ’ป ๐ŸŽจ ๐Ÿค”
Guillermo Angulo
Guillermo Angulo

๐Ÿ› ๐Ÿ’ป
Xavier Civit
Xavier Civit

๐Ÿ›
jpizzle34
jpizzle34

๐Ÿ’ป
Moritz Eck
Moritz Eck

๐Ÿ’ป
B0rk3
B0rk3

๐Ÿ’ป
Nihey Takizawa
Nihey Takizawa

๐Ÿ’ป
Ciro Alabrese
Ciro Alabrese

๐Ÿ’ป
Nik Zaugg
Nik Zaugg

๐Ÿ’ป
Pascal Oberbeck
Pascal Oberbeck

๐Ÿ›
Guillaume REMBERT
Guillaume REMBERT

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

Stargazers โœจ

Stargazers repo roster for @alexzaganelli/strapi-plugin-email-designer

Forkers โœจ

Forkers repo roster for @alexzaganelli/strapi-plugin-email-designer

Support Me โœจ

If you like this plugin I'm very happy, so lets drink a beer. Salute! ๐Ÿป

"Buy Me A Beer"

strapi-plugin-email-designer's People

Contributors

alexzaganelli avatar allcontributors[bot] avatar aoor9 avatar b0rk3 avatar bannerchi avatar creazy231 avatar guilleangulo avatar jpizzle34 avatar meck93 avatar nihey avatar nikzaugg avatar poberbeck avatar pr0gr8mm3r avatar yanicklandry avatar zguig52 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

strapi-plugin-email-designer's Issues

Issues with Strapi welcome page templating with plugin versions >1.0.0

Hi there, first of all thanks for this wonderful plugin.

I'd like to report a strange behaviour I noticed about Strapi welcome page (the one on / route) when I upgraded the plugin from version 1.0.0 to version 1.2.1 (but I can confirm that also 1.0.1 and 1.1.1 are affected).

Removing the plugin is enough to get rid of the problem. I was initially thinking to the modification of the templating tags to {{ }} which happened on 1.2.1, but then I tested also versions before and the problem is always there down to 1.0.1.

Please see the ticket I opened on Strapi repo before understanding that the problem was rather related with this plugin: strapi/strapi#10533

Thanks

Strapi 4 support

I couldn't get Email Designer running with Strapi 4. Is there a way to get it running or are there any plans for Strapi 4 support?

Subject field

I would really appreciate if email designer plugin would have addition subject text field along side name and body.

Mailgun Attachments

Hi there

I've noticed that it is not possible to append e-mail attachments when using mailgun for example.
The reason being that in the current sendTemplatedEmail function, it only allows emailOptions with key attachments but not attachment (as would be needed for mailgun). Basically it assumes that anything that is not attachments is an email address that needs to be checked, which is not always true.

Does not work

 await strapi.plugins['email-designer'].services.email.sendTemplatedEmail(
    {
      to: email,
      from: from,
      attachment: attachment, // <--- does not work
    },
    {
      templateId: null,
      sourceCodeToTemplateId: 7,
    }
  );

because it will throw when it enters the if statement here:

if (key !== 'attachments') {

Maybe it's worth considering to remove the whole email validation from the plugin and the let user be responsible to provide valid addresses? Because various e-mail providers might need or have additional emailOptions that would all result in an error right now.

Or we define keys that we know need to be checked as e-mail addressed such as email, replyTo etc. and forward the rest of the emailOptions object as is.

I can open a PR for this.

Usage question

In Github it is said that templateReferenceId must be used, but two templates can have the same templateReferenceId, how can make difference between them?
ID ReferenceId Name

  1. 1 Template 1 v1
  2. 1 Template 1 v2
  3. 1 Template 1 v3

how i can specify that template with id=3 and referenceId=1 and Name Template 1 v3 will be used to send the email?

[Strapi V4] Deploying Strapi 4.0.7 with this plugin version 2.0.6 gives Unsupported engine

Hello, first of all thanks for this amazing plugin, I already checked it out, it saves me a lot of time building mail templates.

However problem is that after making everything working on local development I cannot deploy to production.
DigitalOcean App engine works with yarn command and throws this error:

yarn add strapi-plugin-email-designer
[3/5] Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version ">=10.16.0 <=14.x.x". Got "16.13.1"
error Found incompatible module.

on localhost with npm install strapi-plugin-email-designer@latest its only warning and I can build and run my project but not on production:

image

Could you please take a look at this issue?

Problems with Strapi 3.6.3

First of all, great work!

We tried to get this awesome plugin work with our strapi 3.6.3 version but on run up, the following error occured.

This would be so awesome, I can help somehow to get this fixed :)

Thank you!!

#12 1.155 > strapi build
#12 1.155
#12 2.149 Building your admin UI with development configuration ...
#12 3.257 โ„น Compiling Webpack
#12 10.79 Error: Module not found: Error: Can't resolve '../../../../helpers/coreTemplateHelper' in '/srv/app/.cache/plugins/strapi-plugin-email-designer/admin/src/containers/Designer'
#12 10.79 at /srv/app/node_modules/strapi-admin/index.js:71:23
#12 10.79 at finalCallback (/srv/app/node_modules/webpack/lib/Compiler.js:257:39)
#12 10.79 at onCompiled (/srv/app/node_modules/webpack/lib/Compiler.js:265:20)
#12 10.79 at /srv/app/node_modules/webpack/lib/Compiler.js:670:21
#12 10.79 at eval (eval at create (/srv/app/node_modules/tapable/lib/HookCodeFactory.js:33:10), :26:1)
#12 10.79 at /srv/app/node_modules/webpack/lib/Compilation.js:1173:13
#12 10.79 at /srv/app/node_modules/webpack/lib/Compilation.js:1096:25
#12 10.79 at /srv/app/node_modules/webpack/lib/Compilation.js:1017:13
#12 10.79 at /srv/app/node_modules/neo-async/async.js:2830:7
#12 10.79 at /srv/app/node_modules/neo-async/async.js:2830:7
#12 10.79 at done (/srv/app/node_modules/neo-async/async.js:2863:11)
#12 10.79 at /srv/app/node_modules/neo-async/async.js:2818:7
#12 10.79 at /srv/app/node_modules/webpack/lib/Compilation.js:1017:13
#12 10.79 at /srv/app/node_modules/neo-async/async.js:2830:7
#12 10.79 at /srv/app/node_modules/neo-async/async.js:2830:7
#12 10.79 at done (/srv/app/node_modules/neo-async/async.js:2863:11)
#12 10.84 npm ERR! code ELIFECYCLE
#12 10.84 npm ERR! errno 1
#12 10.84 npm ERR! [email protected] build: strapi build
#12 10.84 npm ERR! Exit status 1
#12 10.84 npm ERR!
#12 10.84 npm ERR! Failed at the [email protected] build script.
#12 10.84 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#12 10.89
#12 10.89 npm ERR! A complete log of this run can be found in:
#12 10.89 npm ERR! /root/.npm/_logs/2021-06-21T19_58_18_696Z-debug.log

Specify sender's name using the syntax "FirstName LastName <[email protected]>"

Hi All,

I am trying to send an email so that the recipient sees a human-friendly string (that I can specify dynamically), which accompanies the email address, e.g. it could be the sender's full name. However, I get an error when I use the following syntax:

Jane Citizen <[email protected]>

Note: This syntax works when I send a test email from the Strapi Email Plugin Admin UI. Also, when I send an email specifying just the email address, this plugin works fine.

How do I use the syntax described above with this plugin?

Here is a code snippet of how I am calling the sendTemplatedEmail():

// Send booking confirmation
  const sent = await strapi.plugins[
    "email-designer"
  ].services.email.sendTemplatedEmail(
    {
      to: booking.booker.email,
      from: `${location.name} <${location.email}>`,
      replyTo: `${location.name} <${location.email}>`,
    },
    {
      templateId: process.env.CONFIRMATION_EMAIL_TEMPLATE_ID,
    },
    {
      customer: customer,
      location: _.pick(initBooking.location, ["name", "phone", "email"]),
      booking: confirmedBooking,
    }
  );

NODE_VERSION: v14.16.0
strapi: 3.6.2
strapi-plugin-email-designer: 1.1.3
strapi-plugin-email: ^3.6.3
strapi-provider-email-amazon-ses: ^3.6.3

UPDATE: I've created a PR related to this issue here: #46 (comment)

Issue with sendTemplatedEmail

Tried triggering email using sendTemplatedEmail with the following codes but encountered Bad Request 400 error, and the weird part is there was no error message returned. Using v0.4.1.

        try {
            await strapi.plugins['email-designer'].services.email.sendTemplatedEmail(
              {
                to: user.email, // required
                from: '[email protected]', // optional if /config/plugins.js -> email.settings.defaultFrom is set
                replyTo: '[email protected]', // optional if /config/plugins.js -> email.settings.defaultReplyTo is set
              },
              {
                templateId: 4, // required - you can get the template id from the admin panel
                subject: 'Welcome'
              },
              {
                // this object must include all variables you're using in your email template
                project_name: 'Test Mailer',
              }
            );

          } catch (err) {
            strapi.log.debug('๐Ÿ“บ: ', err);
            return ctx.badRequest(null, err);
          }

This is the debug error from Strapi, which is an empty error.

[2021-05-14T07:51:27.462Z] debug ๏ฟฝ๐Ÿ“บ:  
[2021-05-14T07:51:27.464Z] debug POST /auth/local/register (11297 ms) 400

The response from API call is empty as well.

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": {},
  "data": {}
}

Sending email using the old API works but flagged as depreciated.

      await strapi.plugins['email-designer'].services.email.send({
        templateId,
        to,
        from,
        replyTo,
        // subject,
        data: userData,
      });

Couldn't verify whether it's related to the template_id faced by Sendgrid.

Base Url for photos

Hello guys,

Is there a way to have a baseSrcUrl variable inside the template? The use case is that the project will run in multiple environments with different base urls (e.g. localhost:1337, another server's IP address etc). Another app will consume the email templates from strapi, populate the variables with the correct values with the help of a template engine and then send the email. The thing is that with that solution, I cannot preview the email template in strapi because the url is not yet populated.

Is there any way that I can make the previewer work?

<img align="center" th:src="@{โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹http://{โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹baseSrcUrl}โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹/uploads/photo_d9847b7078.png(baseSrcUrl = ${โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹baseSrcUrl}โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹)}โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹โ€‹" alt="photo" width="600" height="200" />

Thank you for your time guys!

Template Duplication: Failure `sourceCodeToTemplateId` not unique!

Bug Description

During the introduction of the new variable sourceCodeToTemplateId I forgot to test and update the duplicate functionality.
Currently, it no longer works as the sourceCodeToTemplateId is just copied and not removed.

Error Message

POST /email-designer/templates/duplicate/6 (106 ms) 500
warn Duplicate entry error: insert into "email_templates" ("bodyHtml", "bodyText", "created_at", "design", "enabled", "name", "sourceCodeToTemplateId", "subject", "tags", "updated_at") values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) returning * - duplicate key value violates unique constraint "email_templates_sourceCodeToTemplateId_unique"
error Error: Duplicate entry 
    at handleDatabaseError (/node_modules/strapi-connector-bookshelf/lib/utils/errors.js:25:11)
    at Object.create (/node_modules/strapi-connector-bookshelf/lib/queries.js:60:14)
    at processTicksAndRejections (node:internal/process/task_queues:94:5)

Unable to edit Strapi's core email templates

Hey,

Thanks for rewriting this awesome plugin โค.

When I try to load one of the core templates, I get a 400 response. Here is the endpoint logged:
http: GET /email-designer/core/user-address-confirmation (27 ms) 400

When the page gets loaded, it is an empty template.

After creating a design, clicking on the "Save design" triggers no action. Nothing happens.

Is there something that I need to change in my settings? What am I missing?

[Strapi V4] ๐Ÿ˜” templates got deleted out of nowhere

damn, well thats a weird one.

all the templates i created are gone, the last trace of what happened :
ive checked before it, nothing was out of the ordinary, all requests were 200

[2022-02-13 00:06:00.882] error: select "t0".* from "email_templates" as "t0" - relation "email_templates" does not exist
error: select "t0".* from "email_templates" as "t0" - relation "email_templates" does not exist
    at Parser.parseErrorMessage ([Project-folder]\node_modules\pg-protocol\dist\parser.js:287:98)
    at Parser.handlePacket ([Project-folder]\node_modules\pg-protocol\dist\parser.js:126:29)     
    at Parser.parse ([Project-folder]\node_modules\pg-protocol\dist\parser.js:39:38)
    at TLSSocket.<anonymous> ([Project-folder]\node_modules\pg-protocol\dist\index.js:11:42)     
    at TLSSocket.emit (node:events:390:28)
    at TLSSocket.emit (node:domain:475:12)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at TLSSocket.Readable.push (node:internal/streams/readable:228:10)
    at TLSWrap.onStreamRead (node:internal/stream_base_commons:199:23)
[2022-02-13 00:06:10.894] http: GET /admin/plugins/email-designer (2 ms) 200
[2022-02-13 00:06:10.913] http: GET /admin/runtime~main.2229d96d.js (2 ms) 200
[2022-02-13 00:06:10.916] http: GET /admin/main.39ff1a78.js (1 ms) 200
[2022-02-13 00:06:11.095] http: GET /admin/project-type (2 ms) 200

im using postgresql as the db, its hosted on heroku

Template editor does not work as expected

Bug report

Describe the bug

When I open the Email designer, I see the table of templates, but when I go to edit the template, the HTML and text tabs are blank. In DevTools. the following error is shown

editor.js:2 RangeError: Incorrect locale information provided
    at Function.supportedLocalesOf (<anonymous>)
    at editor.js:2:4272941
    at q (editor.js:2:4274616)
    at t.getDerivedStateFromProps (editor.js:2:4275246)
    at pi (editor.js:2:4125179)
    at qa (editor.js:2:4147152)
    at Hl (editor.js:2:4188980)
    at Ms (editor.js:2:4175131)
    at ks (editor.js:2:4175059)
    at ws (editor.js:2:4174922)

I have a local dev environment using the same version of Strapi, Node and NPM/Yarn, however the designer works as expected.

System

  • Node.js version: 14.20.0
  • NPM version: 6.14.16 / Yarn 1.22.5
  • Strapi version: 3.6.10
  • Plugin version: 1.1.9
  • Database: PostgreSQL
  • Operating system: Ubuntu 20.0.4

[Strapi V4] Sends only one template and skips the templateId,templateReferenceId params

ive been trying to send other templates i created, but doesnt seem to work.

plugin version: 2.0.5

{
templateId: 3, 
templateReferenceId: 2,
}

the weird thing is that it sends only the first one showing on the list, it skips the given params, if i go and try to update the references to change the order, it'll send the other tempalte instead, no idea why/how its doing this.

image

Unable to run project after installation

Bug report

Describe the bug

After installation I get the following error: error: Could not load js config file /node_modules/strapi-plugin-email-designer/strapi-server.js: Unexpected token '?'
Error: Could not load js config file /node_modules/strapi-plugin-email-designer/strapi-server.js: Unexpected token '?'

Steps to reproduce the behavior

  1. yarn add strapi-plugin-email-designer
  2. yarn build
  3. yarn develop
  4. See error

Expected behavior

Should work

[Bug]: Importing Templates Changes TemplateId

Description

I have created a few templates using the local development environment. Adjusted the email code according to fetch the respective template via its templateId. Everything works great ๐ŸŽ‰ Btw. thanks for the great work!

I exported the templates and tried to import them into our staging environment. But the problem is that the id of the template stored in the JSON file is used to create the templateId during the import. If the id already exists in the database, the templateId changes during the import and, therefore, the old templateId used in the code to fetch the template is no longer correct.

Solution Proposal

We should differentiate between the templateId and the id of the template in the database table. Both must be unqiue but the templateId provided via the id field in the JSON file should never change (on import). The import should rather fail if a template with a given templateId already exists. The goal of this is that the templateId can be used in the code to retrieve the template without worrying that it might change during a template import.

I hope I was able to explain what the problem is. If not, please let me know, I will elaborate further...

[Feature]: API Access to Plugin Endpoints

Current Situation

In the config/routes.json file, for each route the policy "admin::isAuthenticatedAdmin" is defined which means it is required to be an authenticated Admin in order to retrieve or update the templates. In our case, we would like to programmatically backup the email templates. For this, we require to be able to query the /templates endpoint using an API user. We would like to periodically fetch the templates and create a pull request using a bot if they differ from what is stored in the repository.

Idea

Would it be possible to extend or loosen the policies at least for the GET request such that Strapi API users can query the templates? I would have used a Strapi UI/Admin user but it seems that those kind of users can not use the API.
Therefore, I would propose to remove the policy of the GET requests or to adjust the policy to a custom policy.

I think it would make sense to remove the policy as the access privileges of the API users can be controlled via the Settings/User & Permissions Plugin/Roles. By default no API user can access the plugin's routes. With the current policy, it is also not possible to allow an API user to access the plugin's routes even if specifically enabled via the settings.

Current Routes: config/routes.json

{
  "routes": [
    {
      "method": "GET",
      "path": "/templates",
      "handler": "designer.getTemplates",
      "config": {
        "policies": ["admin::isAuthenticatedAdmin"]
      }
    },
    {
      "method": "GET",
      "path": "/templates/:templateId",
      "handler": "designer.getTemplate",
      "config": {
        "policies": ["admin::isAuthenticatedAdmin"]
      }
    },
    {
      "method": "POST",
      "path": "/templates/:templateId",
      "handler": "designer.saveTemplate",
      "config": {
        "policies": ["admin::isAuthenticatedAdmin"]
      }
    },
    ...
  ]
}

Thanks for the feedback. If you need more information or context. Let me know. Would be happy to help with the implementation...

How do you add authentification for cypress

Hello @alexzaganelli
I was testing out the code of your great plugin. I tried running the tests but they stopped at the login. Is there a way you can add authentification credentials (name and password) in an accessible way to make login automatic?

Can we insert dynamic content?

I am trying to create an eshop, which means i need to send the order summary by email. Is it possible to pass a variable (e.g an array of items) and display them in a table somehow?

Attachments

How do i specify attachments? What type are you expecting there?

Designer not loading

Hi,
I updated strapi from v3 to v4 and email-designer is not loading html version at all and text version and reference id I can edit, but it is not saved
I have my config/middleware.js

  'strapi::errors',
  {
    name: 'strapi::security',
    config: {
      contentSecurityPolicy: {
        directives: {
          'script-src': ["'self'", 'editor.unlayer.com'],
          'frame-src': ["'self'", 'editor.unlayer.com'],
          'img-src': ["'self'", 'data:', 'cdn.jsdelivr.net', 'strapi.io', 's3.amazonaws.com'],
        },
      },
    },
  },
  'strapi::cors',
  'strapi::poweredBy',
  'strapi::logger',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
]

I don't have any plugin settings for this library
Can you help me what am I missing?

blank screen Strapi

After installation I get a blank screen
Strapi versions tried: 3.6.2 and 3.6.8

Browser console log shows an error: Prism is not defined

Screenshot 2021-08-29 at 19 35 22

Send mail via graphql

Hey friends.

Nice package! Is there a possibility to send mails - created with designer - with an graphql mutation?

Would be a perfect feature!

I get a white screen when I go to see the public role

I installed your package to add a custom email template. I created a custom / contact endpoint, which sends a message to my email, when making a request to the endpoint I get a Forbidden 403, so I think the endpoint is not activated in the interface, enter roles, publish and get a white screen, is it a bug?

image

[Strapi V4] Cant add custom fonts to the template

Issue:
the fonts list doesnt seem to show any fonts, even after i updated the config, ive rebuilt strapi again but with no luck
image
image

my config:
its the same one provided in Read.me

'email-designer': {
    editor: {
      tools: {
        heading: {
          properties: {
            text: {
              value: 'This is the new default text!'
            }
          }
        }
      },
      options: {
        features: {
          colorPicker: {
            presets: ['#D9E3F0', '#F47373', '#697689', '#37D67A']
          }
        },
        fonts: {
          showDefaultFonts: true,
          customFonts: [
            {
              label: "Anton",
              value: "'Anton', sans-serif",
              url: "https://fonts.googleapis.com/css?family=Anton",
            },
            {
              label: "Lato",
              value: "'Lato', Tahoma, Verdana, sans-serif",
              url: "https://fonts.googleapis.com/css?family=Lato",
            },
          ],
        },
        mergeTags: [
          {
            name: 'Email',
            value: '{{= USER.username }}',
            sample: '[email protected]',
          },
        ]
      },
      appearance: {
        theme: "dark",
        panels: {
          tools: {
            dock: 'left'
          }
        }
      }
    }
  },

URL and TOKEN variables

Thanks for creating this designer plugin.
I've added a button to Set Password core template with the following:
<%= URL %>?code=<%= TOKEN %>
(it's taken from the original template). I've also tried lodash syntax:
{{URL}}?code={{TOKEN}}
but it does not work (URL and TOKEN are empty strings on the inbox side).
Though the first version used as an URL for an tag works as expected.
Is it an issue with Unlayer button or am I missing something?

This does not work:
image
image

This works:
image

Back button doesn't work properly

Bug report

Describe the bug

It refreshes whatever page you're on

Steps to reproduce the behavior

  1. Go to edit a template
  2. Click on go back (to the template navigation screen)
  3. See error

Expected behavior

Always goes to the template navigation

[Strapi V4] the config doesnt seem to do anything

ive updated some fields in the config, but it doesnt seems like its updating anything in the editor,
ive checked where the config gets called, and the request returns an empty html page instead of the config, not sure if its the cause the issue

image

Unable to delete and duplicate a template

Hi there,

Thank you so much for this plugin!
Nevertheless, I stumbled upon this issue:
image

I'm unable to delete or even duplicate a template.
And the console is empty.

Cheers,

Updating to 0.2.9 results in empty templates

Hey just updated to the newest version 0.2.9 and after running yarn && yarn build && yarn develop all my created templates are empty.
Took a look into the network tab and can't see any query to the templates anymore. I think thats the reason for the problem.

Query templates by name

Hello everybody and congratulations on the great work you are doing :)

The issue is that I am trying to get a certain template by its name and not the id and I can't get it to work. I am doing it like this: http://localhost:1337/email-designer/templates?name=Table where Table is the name of the template but I am still getting the array of the templates.

How could I go about implementing this?

Template Import: Failure sourceCodeToTemplateId not unique

Hi everyone,

i encountered a similar issue to #60, when importing templates.
The error message is again that the sourceCodeToTemplateId is not unique:

warn Duplicate entry error: insert into "email_templates" ("bodyHtml", "bodyText", "created_at", "design", "enabled", "name", "sourceCodeToTemplateId", "subject", "tags", "updated_at") values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) returning * - duplicate key value violates unique constraint "email_templates_sourceCodeToTemplateId_unique"
error Error: Duplicate entry 
    at handleDatabaseError (/node_modules/strapi-connector-bookshelf/lib/utils/errors.js:25:11)
    at Object.create (/node_modules/strapi-connector-bookshelf/lib/queries.js:60:14)
    at processTicksAndRejections (node:internal/process/task_queues:94:5)

Strapi 4.0.8: Could not load js config file node_modules\strapi-plugin-email-designer\strapi-server.js

Cant't start dev server after plugin installation:

Building your admin UI with development configuration
i Compiling Webpack
โˆš Webpack: Compiled successfully in 10.90s
Admin UI built successfully
[2022-02-17 15:08:23.951] debug: โ›”๏ธ Server wasn't able to start properly.
[2022-02-17 15:08:23.953] error: Could not load js config file .\node_modules\strapi-plugin-email-designer\strapi-server.js: Unexpected token '?'
Error: Could not load js config file .\node_modules\strapi-plugin-email-designer\strapi-server.js: Unexpected token '?'

at loadJsFile (.\node_modules@strapi\strapi\lib\core\app-configuration\load-config-file.js:18:11)
at loadFile (.\node_modules@strapi\strapi\lib\core\app-configuration\load-config-file.js:35:14)
at Object.loadPlugins (.\node_modules@strapi\strapi\lib\core\loaders\plugins\index.js:96:26)
at async Strapi.loadPlugins (.\node_modules@strapi\strapi\lib\Strapi.js:277:5)
at async Promise.all (index 1)
at async Strapi.register (.\node_modules@strapi\strapi\lib\Strapi.js:309:5)
at async Strapi.load (.\node_modules@strapi\strapi\lib\Strapi.js:407:5)
at async Strapi.start (.\node_modules@strapi\strapi\lib\Strapi.js:161:9)

Not everything is emails in the `emailOptions`

To attach files to emails, you need to pass them in the emailOptions variables under the key attachments variable and assign a list of objects to it.

Object.entries(emailOptions).forEach(([key, address]) => {
if (Array.isArray(address)) {
address.forEach((email) => {
if (!isValidEmail.test(email)) throw new Error(`Invalid "${key}" email address with value "${email}"`);
});
} else {
if (!isValidEmail.test(address)) throw new Error(`Invalid "${key}" email address with value "${address}"`);
}
});

Possible solution:
Skip the validation for the attachment key:

if(key !== "attachments") {
...
}

Error interpolating variables inside headings

Hey, first of all thanks for creating this awesome plugin! ๐Ÿ˜ƒ

Description

When adding a variable at data object param (in sendTemplatedEmail), and used in the template inside a heading tag, lodash throws a ReferenceError. I think this is happening because the htmlToText function parses headings to uppercase, creating a mismatch when interpolating.

For example, using a variable total inside the data param:

At the template At the parsed bodyText
shot_210610_182016 shot_210610_173236

error

Opened a possible solution at #37

Strapi v4, html and design variables never get filled.

While saving a template the html part doesn't get saved while the text part does. Analysing the React component it looks like that the variables design and html never receive their value from a function.
V 2.0.0 Strapi V 4.0.7

Doesn't work with Strapi v4.1.8

Bug report

Describe the bug

Steps to reproduce the behavior

Expected behavior

There is a babel error after upgrading Strapi to v4.1.8

Screenshots

image

Code snippets

If applicable, add code samples to help explain your problem.

System

  • Node.js version:
  • NPM version: 8.x
  • Strapi version: 4.1.8
  • Plugin version: 2.1.0
  • Database: postgresql
  • Operating system: windows

Additional context

Add any other context about the problem here.

template_id error with sendgrid

Hello!

I was playing around with this plugin along with sendgrid as the email provider and I ran into this issue

image

This is the code/endpoint that I am testing

    testEmail: async (ctx) => {
        try {
            await strapi.plugins['email-designer'].services.email.sendTemplatedEmail(
              {
                to: '[email protected]', // required
                from: '[email protected]', // optional if /config/plugins.js -> email.settings.defaultFrom is set
                replyTo: '[email protected]', // optional if /config/plugins.js -> email.settings.defaultReplyTo is set
              },
              {
                templateId: 6, // required - you can get the template id from the admin panel
                subject: `Welcome to My Project`, // If provided here will override the template's subject. Can include variables like `Welcome to <%= project_name %>`
              },
              {
                // this object must include all variables you're using in your email template
                project_name: 'Test Mailer',
              }
            );

          } catch (err) {
            strapi.log.debug('๐Ÿ“บ: ', err);
            return ctx.badRequest(null, err);
          }
          
          return "Success!"
    }

I believe this issue might be related to sendgrid supporting a templating feature as well along with the fact that the templateId is being passed along here:

return strapi.plugins.email.provider.send({ ...emailOptions, ...templatedAttributes });

If passing this templateId is not strictly required on that line then perhaps removing it might be the quickest solution? Please correct me if I am wrong but I don't see why the email provider would need to know anything about what the templateId is.

Thank you! Keep up the awesome work!

โš ๏ธ Update / Fork with breaking changes

Hello Alexandre. First of all thank you for the possibility to design email templates in Strapi.
I tried the plugin, but I encountered several errors in the latest version of Strapi with Lodash templating.

I have forked your project and made some adjustments. If you feel like it, you can check it out. The README should be mostly updated as well. Please note, that these adjustments include breaking changes.

Link: https://github.com/creazy231/strapi-plugin-email-designer

I would be really happy to make PRs in the future as well.

Features my fork includes:

  • Automatically generate Text from HTML if there is no given Text Template.
  • Use official Lodash Templating format. Example: <%= variable %>
  • Use official Strapi syntax to send emails
  • Updated Tests to switch language to english

All changes I've made are documented in this commit: creazy231@5993774

Cannot duplicate a template

Hi,

First thanks for the very good job and the quality of this project. I started to use it. I found a small issue on the latest version.

The DB column email_templates_sourceCodeToTemplateId has a unique constraint and when duplicating, the insert request is trying to insert this value, raising an error:
warn Duplicate entry Error: insert into email_templates (bodyHtml, bodyText, created_at, design, enabled, name, sourceCodeToTemplateId, subject, tags, updated_at) values [...] ER_DUP_ENTRY: Duplicate entry '0' for key 'email_templates_sourceCodeToTemplateId_unique'

error Error: Duplicate entry
at handleDatabaseError (/srv/app/node_modules/strapi-connector-bookshelf/lib/utils/errors.js:25:11)
at Object.create (/srv/app/node_modules/strapi-connector-bookshelf/lib/queries.js:60:14)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Object.create (/srv/app/node_modules/strapi-database/lib/queries/helpers.js:15:18)
at async /srv/app/node_modules/strapi/lib/middlewares/router/utils/routerChecker.js:79:22
at async /srv/app/node_modules/strapi-utils/lib/policy.js:68:5
at async /srv/app/node_modules/strapi/lib/middlewares/parser/index.js:48:23
at async /srv/app/node_modules/strapi/lib/middlewares/xss/index.js:26:9

I have tried to remove the value I had setted here in the origin template and saved it, but it seems that it then uses a default 0 value when duplicating it.

I think this field "sourceCodeToTemplateId" shall not be part of the duplication action.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.