Is it possible to send messages, through your NewsmanSMTP account, using templates ? It sure is !
You can use templates for sending as well as create them in our system. NewsmanSMTP templates support handlebars as a templateing engine.
1) Create a template
First, we need a template to use when sending a message. Templates can be created in two ways:
1.1) Using the NewsmanSMTP API
Our API offers several methods which you can use in your app to create and update templates.
Documentation can be found here.
1.2) Using the manager interface
You can find the templates section in the Transactional -> Templates submenu.
To create a template, use the “Create a template” button which is located above the listing. When creating, you have to fill in a few fields:
- Template ID, an identifier that should be specified in the parameters when you want to use a template. It has to be unique on the account. Please enter only lowercase letters or numbers or underscores, no special characters, no spaces.
Use | for grouping. Example: register_email|en - Type, refers to the way templates can be modified after creation
- Subject, use if you want to replace the email subject when sending
After creating a template, several options appear in the listing:
When editing a template, if a template group has multiple templates, a dropdown will de displayed which allows for easier switching between them:
After you finish editing, a template may look like this:
You can use the “Preview” to see how your template looks using a certain dataset. For this example, we have used this JSON code:
{ "firstname":"John", "lastname":"Doe", "options":[ {"title": "foo1", "value": "bar1"}, {"title": "foo2", "value": "bar2"} ] }
2) Send using a template
You can use the template for sending in two ways:
2.1) API
The API can be used to send a template. The method is documented here.
2.2) SMTP
If you wish to send a template via SMTP then all you have to do is:
- Specify the desired template_id as a header with the name X-NZ-MailTemplate
- The body of the email should be a text which represents the JSON encoded data that will be fed to the template when sending
Below you can find an example using Zend Mail:
$msg = new Zend_Mail("utf-8"); $msg->setMessageId(true); // auto message id $msg->setDate(); $msg->setFrom("john@example.com", "John Doe"); $msg->setSubject("Example subject"); $template = "example_templates|example1"; $example_data = array( "firstname" => "John", "lastname" => "Doe", "options" => array( array("title" => "foo1", "value" => "bar1"), array("title" => "foo2", "value" => "bar2") ) ); $msg->setBodyText(json_encode($example_data), 'utf-8', Zend_Mime::ENCODING_QUOTEDPRINTABLE); $msg->addHeader("X-NZ-MailTemplate", $template);
Note: NewsmanSMTP templates support handlebars version 2 (“else if” is currently not supported).