Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork20
API Mail Adapter for Parse Server
License
parse-community/parse-server-api-mail-adapter
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The Parse Server API Mail Adapter enables Parse Server to send emails using any 3rd party API with built-in dynamic templates and localization.
ℹ️ This repository has been transferred to the Parse Platform Organization on May 15, 2022. Please update any links that you may have to this repository, for example if you cloned or forked this repository and maintain a remote link to this original repository, or if you are referencing a GitHub commit directly as your dependency.
- Install adapter:
npm install --save parse-server-api-mail-adapter - Addtemplate files to a subdirectory.
- Addadapter configuration to Parse Server.
The demo script makes it easy to test adapter configurations and templates by sending emails without Parse Server via the email service providerMailgun:
- Create a file
mailgun.jsonin thedemodirectory with the following content:{"key":"MAILGUN_API_KEY",// e.g. abc123"domain":"MAILGUN_DOMAIN",// e.g. sandbox-example@mailgun.org"sender":"SENDER_EMAIL",// e.g. sender@example.com"recipient":"RECIPIENT_EMAIL"// e.g. recipient@example.com}
- Run
node ./demoto execute the script and send an email.
You can modify the script to use any other API you like or debug-step through the sending process to better understand the adapter internals.
An example configuration to add the API Mail Adapter to Parse Server could look like this:
constMailgun=require('mailgun.js');constformData=require('form-data');const{ ApiPayloadConverter}=require('parse-server-api-mail-adapter');// Configure mail clientconstmailgun=newMailgun(formData);constmailgunClient=mailgun.client({username:'api',key:process.env.MAILGUN_API_KEY});constmailgunDomain=process.env.MAILGUN_DOMAIN;// Configure Parse Serverconstserver=newParseServer({ ...otherServerOptions,emailAdapter:{module:'parse-server-api-mail-adapter',options:{// The email address from which emails are sent.sender:'sender@example.com',// The email templates.templates:{// The template used by Parse Server to send an email for password// reset; this is a reserved template name.passwordResetEmail:{subjectPath:'./files/password_reset_email_subject.txt',textPath:'./files/password_reset_email.txt',htmlPath:'./files/password_reset_email.html'},// The template used by Parse Server to send an email for email// address verification; this is a reserved template name.verificationEmail:{subjectPath:'./files/verification_email_subject.txt',textPath:'./files/verification_email.txt',htmlPath:'./files/verification_email.html'},// A custom email template that can be used when sending emails// from Cloud Code; the template name can be chosen freely; it// is possible to add various custom templates.customEmail:{subjectPath:'./files/custom_email_subject.txt',textPath:'./files/custom_email.txt',htmlPath:'./files/custom_email.html',// Placeholders are filled into the template file contents.// For example, the placeholder `{{appName}}` in the email// will be replaced the value defined here.placeholders:{appName:"ExampleApp"},// Extras to add to the email payload that is accessible in the// `apiCallback`.extra:{replyTo:'no-reply@example.com'},// A callback that makes the Parse User accessible and allows// to return user-customized placeholders that will override// the default template placeholders. It also makes the user// locale accessible, if it was returned by the `localeCallback`,// and the current placeholders that will be augmented.placeholderCallback:async({ user, locale, placeholders})=>{return{phone:user.get('phone');};},// A callback that makes the Parse User accessible and allows// to return the locale of the user for template localization.localeCallback:async(user)=>{returnuser.get('locale');}}},// The asynchronous callback that contains the composed email payload to// be passed on to an 3rd party API and optional meta data. The payload// may need to be converted specifically for the API; conversion for// common APIs is conveniently available in the `ApiPayloadConverter`.// Below is an example for the Mailgun client.apiCallback:async({ payload, locale})=>{constmailgunPayload=ApiPayloadConverter.mailgun(payload);awaitmailgunClient.messages.create(mailgunDomain,mailgunPayload);}}}});
Emails are composed using templates. A template defines the paths to its content files, for example:
templates:{exampleTemplate:{subjectPath:'./files/custom_email_subject.txt',textPath:'./files/custom_email.txt',htmlPath:'./files/custom_email.html',}},
There are different files for different parts of the email:
- subject (
subjectPath) - plain-text content (
textPath) - HTML content (
htmlPath)
See thetemplates for examples how placeholders can be used.
Placeholders allow to dynamically insert text into the template content. The placeholder values are filled in according to the key-value definitions returned by the placeholder callback in the adapter configuration.
This is using themustache template syntax. The most commonly used tags are:
{{double-mustache}}: The most basic form of tag; inserts text as HTML escaped by default.{{{triple-mustache}}}: Inserts text with unescaped HTML, which is required to insert a URL for example.
By default, the following placeholders are available in the password reset and email verification templates:
{{appName}}: The app name as set in the Parse Server configuration.{{username}}: The username of the user who requested the email.{{link}}: The URL to the Parse Server endpoint for password reset or email verification.
Localization allows to use a specific template depending on the user locale. To turn on localization for a template, add alocaleCallback to the template configuration.
The locale returned bylocaleCallback will be used to look for locale-specific template files. If the callback returns an invalid locale or nothing at all (undefined), localization will be ignored and the default files will be used.
The locale-specific files are placed in sub-folders with the name of either the whole locale (e.g.de-AT), or only the language (e.g.de). The locale has to be in format[language]-[country] as specified inIETF BCP 47, e.g.de-AT.
Localized files are placed in sub-folders of the given path, for example:
base/├──example.html// default file└──de/// de language folder│└──example.html// de localized file└──de-AT/// de-AT locale folder│└──example.html// de-AT localized file
Files are matched with the user locale in the following order:
- Locale (locale
de-ATmatches file in folderde-AT) - Language (locale
de-ATmatches file in folderdeif there is no file in folderde-AT) - Default (default file in base folder is returned if there is no file in folders
de-ATandde)
Sending an email directly from Cloud Code is possible since Parse Server > 4.5.0. This adapter supports this convenience method.
If theuser provided has an email address set, it is not necessary to set arecipient because the mail adapter will by default use the mail address of theuser.
Parse.Cloud.sendEmail({templateName:"next_level_email",placeholders:{gameScore:100,nextLevel:2},user:parseUser// user with email address});
| Parameter | Type | Optional | Default Value | Example Value | Description |
|---|---|---|---|---|---|
sender | String | - | from@example.com | The email sender address; overrides the sender address specified in the adapter configuration. | |
recipient | String | - | to@example.com | The email recipient; if set overrides the email address of theuser. | |
subject | String | - | Welcome | The email subject. | |
text | String | - | Thank you for signing up! | The plain-text email content. | |
html | String | yes | undefined | <html>...</html> | The HTML email content. |
templateName | String | yes | undefined | customTemplate | The template name. |
placeholders | Object | yes | {} | { key: value } | The template placeholders. |
extra | Object | yes | {} | { key: value } | Any additional variables to pass to the mail provider API. |
user | Parse.User | yes | undefined | - | The Parse User that the is the recipient of the email. |
This adapter supports any REST API by adapting the API payload in the adapter configurationapiCallback according to the API specification.
For convenience, support for common email provider APIs is already built into this adapter and available via theApiPayloadConverter.
The following is a list of currently supported API providers. If the provider you are using is not already supported, please feel free to open an issue.
Caution
The code examples below may show sensitive data such as API keys to be stored as environment variables. This is not a recommended practice and only used for simplicity to demonstrate how an adapter can be set up for development.
This is an example for the AWS Simple Email Service client using the AWS JavaScript SDK v3:
const{SES, SendEmailCommand}=require('@aws-sdk/client-ses');const{// Get credentials via IMDS from the AWS instance (when deployed on AWS instance) fromInstanceMetadata,// Get AWS credentials from environment variables (when testing locally) fromEnv,}=require('@aws-sdk/credential-providers');// Get AWS credentials depending on environmentconstcredentialProvider=process.env.NODE_ENV=='production' ?fromInstanceMetadata() :fromEnv();constcredentials=awaitcredentialProvider();// Configure mail clientconstsesClient=newSES({ credentials,region:'eu-west-1',apiVersion:'2010-12-01'});// Configure Parse Serverconstserver=newParseServer({// ... other server optionsemailAdapter:{module:'parse-server-api-mail-adapter',options:{// ... other adapter optionsapiCallback:async({ payload, locale})=>{constawsSesPayload=ApiPayloadConverter.awsSes(payload);constcommand=newSendEmailCommand(awsSesPayload);awaitsesClient.send(command);}}}});
This is an example for the Mailgun client:
// Configure mail clientconstmailgun=require('mailgun.js');constmailgunClient=mailgun.client({username:'api',key:process.env.MAILGUN_API_KEY});constmailgunDomain=process.env.MAILGUN_DOMAIN;// Configure Parse Serverconstserver=newParseServer({// ... other server optionsemailAdapter:{module:'parse-server-api-mail-adapter',options:{// ... other adapter optionsapiCallback:async({ payload, locale})=>{constmailgunPayload=ApiPayloadConverter.mailgun(payload);awaitmailgunClient.messages.create(mailgunDomain,mailgunPayload);}}}});
This is an example for the ZeptoMail Service client using the ZeptoMail JavaScript SDK.Provide comma separated email adddresses in recepient parameter to send to multiple.
const{ SendMailClient}=require('zeptomail');// Configure mail clientconsturl=process.env.ZEPTOMAIL_URL;consttoken=process.env.ZEPTOMAIL_TOKEN;constzeptoMaiClient=newSendMailClient({ url, token});// Configure Parse Serverconstserver=newParseServer({// ... other server optionsemailAdapter:{module:'parse-server-api-mail-adapter',options:{// ... other adapter optionsapiCallback:async({ payload, locale})=>{constzeptoMailPayload=ApiPayloadConverter.zeptomail({api:'1.1', payload});awaitzeptoMaiClient.sendMail(zeptoMailPayload);},}}});
This is an example of how the API payload can be adapted in the adapter configurationapiCallback according to a custom email provider's API specification.
// Configure mail clientconstcustomMail=require('customMail.js');constcustomMailClient=customMail.configure({ ...});// Configure Parse Serverconstserver=newParseServer({// ... other server optionsemailAdapter:{module:'parse-server-api-mail-adapter',options:{// ... other adapter optionsapiCallback:async({ payload, locale})=>{constcustomPayload={customFrom:payload.from,customTo:payload.to,customSubject:payload.subject,customText:payload.text};awaitcustomMailClient.sendEmail(customPayload);}}}});
About
API Mail Adapter for Parse Server
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors8
Uh oh!
There was an error while loading.Please reload this page.