Overview

The Email service allows you to send emails by making a simple REST call. You can achieve this by providing the content of the emails, or by using the templating system in the Velocity Template service.

Use the Email service to send transactional emails to a single user as a result of a user-triggered action. The service support emails of these types and more:

  • welcome emails
  • shipping notices
  • order confirmations
  • password reminders
  • purchase receipts

Use the Email service together with the Velocity Template service's templating system to:

  • Create and manage email templates for any use case.
  • Customize emails for each recipient using the Velocity Template Language.
  • Create localized email templates for different languages and locations.
Do not use the Email service for bulk, marketing, or commercial emails. These types of emails must be processed in bulk, which the Email service does not support. When the service detects a mass-mailing, it automatically blocks all further requests and issues response code 429.

Example use cases

Here are some of the many ways you can use the Email service:

  • Send a customer an order confirmation email that includes order details.
  • Email an employee an invitation to create a new employee account.
  • Send a customer a password reset email.


API Reference

/send

Adds an email to the email sending queue, causing it to be eventually sent to the specified recipient.

/send

post

Queues an email for sending and returns immediately.

Optionally, allows to use the specified template to render the subject and body of the email and then passes the given attribute values to that template. All of these inputs are passed in the request body. See its JSON schema for details.

In order to send an email with attachments use the multipart/form-data MIME type.

The caller must have the hybris.email_send or hybris.email_admin scope assigned.

/send-sync

Sends an email to the specified recipient.

/send-sync

post

Sends an email to the specified recipient.

Optionally, allows to use the specified template to render the subject and body of the email and then passes the given attribute values to that template. All of these inputs are passed in the request body. See its JSON schema for details.

In order to send an email with attachments use the multipart/form-data MIME type.

The caller must have the hybris.email_send or hybris.email_admin scope assigned.


Limitations

Bulk emails

Do not use the Email service for bulk, marketing, or commercial emails. The Email service does not support bulk email procesing. When the service detects a mass-mailing, it automatically blocks all further requests and issues the response code 429.

Send emails from a custom domain

Before you can send emails from your custom domain, you must register the domain in the Email Service to prove that you are its owner. For more information, refer to the Sending from your own Domain documentation.

Until you have registered your custom domain, your fromAddress must belong to the domain {project}.mail.yaas.io, where {project} is the ID of your project. For example: john.doe@{project}.mail.yaas.io.


Email Sending

To send a message using the Email service, you can:

  • Use the body and subject fields, which send an email with a YaaS-styled template.
  • Use the bodyTemplate with the template code _blank to send an email with no styling, or the styling you pass with the definable attribute content.
  • Use the bodyTemplate field to reference your own template defined with the Velocity Template service. You can also customize the contents of the message by passing data into the template itself.

You must also specify some additional information, most notably the recipient of the specific message.

The Email service provides two, functionally-equivalent alternatives for triggering the sending of an email message.

  • Using /send does most of the involved processing asynchronously and responds to the caller as quickly as possible.
  • Using /send-sync does most of the processing synchronously and only responds to the caller afterwards.

The sections in this topic describe the information to provide when sending an email, and the two alternative methods, as well as the trade-offs between them, in more detail.

Payload attributes for sending an email

You can provide this information when sending an email:

  • fromAddress and fromName
    • The email address and name to use in the From header of the email
    • The domain portion of the fromAddress is currently limited to {yourProjectId}.mail.yaas.io. For example: john.doe@{yourProjectId}.mail.yaas.io.
    • To avoid this restriction and use your own domain in the fromAddress, please refer to the documentation on Sending from your own Domain or Custom SMTP Server Integration.
  • replyToAddress and replyToName
    • The email address and name to use in the Reply-To header of the email
    • If you do not provide replyToAddress and replyToName, the Reply-To header sets to fromAddress and fromName. You can not provide replyToName without replyToAddress.
  • toAddress and toName
    • The email address and name to use in the To header of the email
    • Use your own valid email address here for testing. This allows you to verify the successful transmission of the email and review its contents.
    • If you don't need to check the contents of the email, you can use any email belonging to the test domain **@yaastest.com**. When you use an email from that domain, the service does not send an email.
  • to
    • Alternatively, or in addition to providing the toAddress and toName, you can specify multiple primary recipients here. Each element of the list must contain an address attribute for the email address, and a name attribute for the full name of the recipient. If you include multiple recipients, the system uses this list in the To header of the email, prepended with the toAddress and toName, if specified.
    • If the first address in the resulting To email header belongs to the test domain **@yaastest.com**, the service does not send an email.
  • cc
    • Specify your carbon copy (CC) recipients here. Each element of the list must contain an address attribute for the email address, and a name attribute for the full name of the recipient. If you include CC recipients, the system uses this list in the Cc header of the email.
  • bcc

    • Specify your blind carbon copy (BCC) recipients here. Each element of the list must contain an address attribute for the email address, and a name attribute for the full name of the recipient. If you add BCC recipients, the service uses this list in the Bcc header of the email.
  • subject

    • The text to use as the subject of the email
  • body

    • The text or HTML code to use as the body of the email. This content is wrapped in the YaaS-styled template.
  • subjectTemplate and/or bodyTemplate

    • Use these parameters to refer to a template defined and rendered with the Velocity Template service. You can use these parameters instead of the subject and/or body fields.
    • Each of these fields can include these attributes:

      • code and owner
        • Together, these properties identify the template from the Velocity Template service to use for the content of the email. See the "Upload Your Template" tutorial for more information.
        • If you do not specify the owner attribute, the system uses the {client} as the owner value.
        • When you specify _blank as code, you can directly define the body of the email by entering it in the ${content} attribute. See the attributes field below.|
      • variant and fallbackVariants
        • The variant to use for template rendering. If you do not define this value for the template, the system sues the first existing variant from the fallbackVariants instead.
      • locale
        • The locale to use for template rendering. It transmits to the Velocity Template service as part of the render request. If you do not define this value for the template, the system uses the system default value instead.
      • attributes
        • A list of attribute names and values to pass to the Velocity Template service for the template rendering. The values passed here replace the placeholders defined in the Velocity templates. For this example, include the attributes from the Velocity template file introduced in the "Create Your Template" tutorial: customerName, couponValue, and couponCode.

These are the required attributes:

  • fromAddress
  • at least one toAddress, or a not-empty list of to

Asynchronous email sending

Send a POST request to the /send resource of the Email service to trigger the asynchronous sending of a message.

Asynchronous sending means that the Email service queues the outgoing email and processes it after the request. A request to the async resource always returns immediately. However, because the system must queue the emails first, it could take up to several minutes until the system actually sends the email, depending on the service load.

Be aware that a successful response from the async resource only means that the email is successfully queued. It does not mean that the email template successfully rendered or that the message was handed over to the outgoing mail server. For example, if the referenced template does not exist, the Email service still returns a successful response, even though processing will later fail when the system tries to render the email. Similarly, if a recipient's email address is incorrect, the system provides no notification. For that reason, when you use asynchronous email sending, always verify beforehand that the data in the send request is correct.

Synchronous email sending

Trigger synchronous email sending through a POST request to the /send-sync resource of the Email service.

This approach gives you instant feedback in case something goes wrong when sending the email, and thus facilitates troubleshooting. However, when you apply your knowledge in a production scenario, you might prefer using asynchronous email sending instead.

A request to the sync resource only responds after the message renders and is ready to be handed over to the outgoing mail server. If there is any error during processing, the sync resource responds with an error status. Therefore, when you receive a successful response, you can assume that the email rendered and processed successfully.

However, subsequent errors might arise after the mail arrives at the outgoing mail server, but before delivery to the intended recipient. In that case, the Email server does not notify the caller of the error. This limitation arises from the nature of email sending itself, and not from the service.

Synchronous email sending requests might take longer then asynchronous requests. A response time of several seconds is not unusual.

To test the Email service without sending actual emails, for performance tests or business logic testing for example, use the test domain **@yaastest.com** in the destination email address. For example:

john.doe.will.not.get.this.email@yaastest.com

The Email service detects the test domain from the destination address and, although it processes the request, it does not send the email to the SMTP server.


Email Sending With Attachments

You can add attachments to any emails you send using the Email service, including emails that use templates.

To send an email with attachments, set the request type to multipart/form-data. This request type still carries the JSON payload described in the Email Sending topic, but adds the attached files to the payload. Define the JSON payload in a form-data field named data and all files in a repeatable field named file.

This example request attaches one file:

curl -v -i -X POST -H "Content-Type: multipart/form-data" -F 'data={"toAddress": "toaddress@somedomain.com", "fromAddress": "seal@yourProject.mail.yaas.io", "toName": "persons name", "fromName": "other persons name", "subject" : "a subject", "body": "a body"}' -F "file=@attachment.pdf" https://api.beta.yaas.io/hybris/email/v2/send

This example request attaches two files:

curl -v -i -X POST -H "Content-Type: multipart/form-data" -F 'data={"toAddress": "toaddress@somedomain.com", "fromAddress": "seal@yourProject.mail.yaas.io", "toName": "persons name", "fromName": "other persons name", "subject" : "a subject", "body": "a body"}' -F "file=@attachment.pdf" -F "file=@attachment2.txt" https://api.beta.yaas.io/hybris/email/v2/send

Limitations

The attachments filename length is limited to 255 characters. The Email service accepts all file attachment types except for attachments with the file extensions listed:

.ade.adp.app.asp.bas.bat.cer
.chm.cmd.com.cpl.crt.csh.der
.exe.fxp.gadget.hlp.hta.inf.ins
.isp.its.js.jse.ksh.lib.lnk
.mad.maf.mag.mam.maq.mar.mas
.mat.mau.mav.maw.mda.mdb.mde
.mdt.mdw.mdz.msc.msh.msh1.msh2
.mshxml.msh1xml.msh2xml.msi.msp.mst.ops
.pcd.pif.plg.prf.prg.reg.scf
.scr.sct.shb.shs.sys.ps1.ps1xml
.ps2.ps2xml.psc1.psc2.tmp.url.vb
.vbe.vbs.vps.vsmacros.vss.vst.vsw
.vxd.ws.wsc.wsf.wsh.xnk
Some ISPs have further limitations, for example in regard to archived attachments, so it is recommended that you test your email sending capabilities through major ISPs before you send your production email.
The system scans attachments for viruses and drops any emails that contain infected attachments.

Code examples

The following are code examples of how to construct a payload with attachments using Jersey and Spring MVC. The examples shown construct the payload with an imaginary file, located at the sample URL https://exampleurl.com/terms_and_conditions_en.pdf, and appears in the email as an attachment called Terms and Conditions.pdf.

The payload of the request for sending attachments is of the MIME type multipart/form-data. The part called data is mandatory and contains the same JSON payload as the application/json request, in plain text. The following specifies the Java object that contains this request, which you can later serialize as a string:

public class EmailRequestData {
    private String toAddress;
    private String fromAddress;
    private String toName;
    private String subject;
    private String body;

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public void setToName(String toName) {
        this.toName = toName;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getToAddress() {
        return toAddress;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public String getToName() {
        return toName;
    }

    public String getSubject() {
        return subject;
    }

    public String getBody() {
        return body;
    }
}

As mentioned, you can serialize such objects later. The following is an example method for serializing these objects:

   final EmailRequestData emailRequestData = new EmailRequestData();
   // fill in the emailRequestData...
   final ObjectMapper mapper = new ObjectMapper();

For the following examples, you need emailRequestDataAsString.

In the examples that follow, the Authorization header value is hardcoded to show the concept. In your actual code, use one of the Authorization libraries.

Jersey implementation

For the Jersey implementation, make sure that you have the jersey-media-multipart dependency in your Maven project's pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey.version}</version>
</dependency>

First, register the MultiPartFeature in your Jersey client:

final Client client = ClientBuilder.newClient().register(MultiPartFeature.class);

In the Jersey implementation, use the org.glassfish.jersey.media.multipart classes.

try (final InputStream attachmentData = new java.net.URL("https://exampleurl.com/terms_and_conditions_en.pdf").openStream()){
    //Create the object for multipart request
    final FormDataMultiPart multiPartData = new FormDataMultiPart();

    //Add the email request body data
    multiPartData.bodyPart(new FormDataBodyPart("data", emailRequestDataAsString, MediaType.TEXT_PLAIN_TYPE));

    //Add the attachment
    final FormDataContentDisposition attachment = FormDataContentDisposition.name("file").fileName("Terms and Conditions.pdf").build();
    multiPartData.bodyPart(new FormDataBodyPart("file", attachmentData, MediaType.APPLICATION_OCTET_STREAM_TYPE).contentDisposition(attachment));

    //Here you can add further attachments

    //Create the payload
    final Entity<FormDataMultiPart> payload = Entity.entity(multiPartData, MediaType.MULTIPART_FORM_DATA);

    //Use the payload in your request
    final Response response = client
        .target(EMAIL_SERVICE_URL)
        .path("send")
        .request()
        .header(HttpHeaders.AUTHORIZATION, "Bearer validAccessToken")
        .post(payload);
}

Spring implementation

If you do not use Jersey, you might be interested in the Spring implementation shown here. It uses the classes from the org.springframework package's subpackages.

try (final InputStream attachmentData = new java.net.URL("https://exampleurl.com/terms_and_conditions_en.pdf").openStream()) {
    //Create the object for multipart request
    final MultiValueMap<String, Object> multiPartData = new LinkedMultiValueMap<>();

    //Add the email request body data
    final HttpHeaders part = new HttpHeaders();
    part.setContentType(org.springframework.http.MediaType.TEXT_PLAIN);
    multiPartData.add("data", new HttpEntity<>(emailRequestDataAsString, part));

    //Add the attachment
    final byte[] attachmentBytes = IOUtils.toByteArray(attachmentData);
    final HttpHeaders bodyPartHeaders = new HttpHeaders();

    bodyPartHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
    bodyPartHeaders.setContentDispositionFormData("file", "Attachment name Example.pdf");
    multiPartData.add("file", new HttpEntity<>(attachmentBytes, bodyPartHeaders));

    //Here you can add further attachments

    //Use the payload in your request
    final HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, "Bearer validAccessToken");
    headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);

    final HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multiPartData, headers);
    final java.net.URI serviceUri = UriComponentsBuilder.fromHttpUrl(EMAIL_SERVICE_URL).pathSegment("send").build().encode().toUri();
    final ResponseEntity<String> response = new RestTemplate().exchange(serviceUri, HttpMethod.POST, requestEntity, String.class);
}


Velocity Template Service Integration

The Email service can use the Velocity Template service to customize emails. Create an email send request using the subjectTemplate and/or bodyTemplate attributes instead of subject and/or body. The service uses the information from these attributes to identify the templates and render them as the body and subject content of the email.

The mailContext variable

Along with the attributes passed to the Velocity Template service for rendering a template, the service also passes the mailContext variable.

The variable data.mailContext (aliased to data.mc or d.mc) holds data taken from the email send request itself. This data is available:

  • ${data.mailContext.toAddress}:
    The email address of the first recipient, such as `tom.jones@hybris.com`.
  • ${data.mailContext.toName}:
    The full name of the first recipient, such as Tom Jones.
  • ${data.mailContext.to}:
    The list of all primary recipients. Each list item is a map that includes the field address for storing the recipient's email address, and the field name for storing the recipient's full name.
  • ${data.mailContext.cc}:
    The list of all carbon copy (CC) recipients. Each list item is a map that includes the field address for storing the recipient's email address, and the field name for storing the recipient's full name.
  • ${data.mailContext.bcc}:
    The list of all blind carbon copy (BCC) recipients. Each list item is a map that includes the field address for storing the recipient's email address, and the field name for storing the recipient's full name.
  • ${data.mailContext.fromAddress}:
    The email address from which the email is sent, such as `noreply@hybris.com`.
  • ${data.mailContext.fromName}:
    The full name of the sender of the email, such as Thomas Jones.
  • ${data.mailContext.replyToAddress}:
    The email reply address, such as `support@hybris.com`.
  • ${data.mailContext.replyToName}:
    The full name for the email reply, such as Support.

For examples of how to use these tools in the context of the Email service, see the advanced templating tutorials on leveraging structured data and securing your templates.


Send Emails from Your Own Domain

By default, the Email service restricts the domain portion of the fromAddress when sending an email message. The domain must comply with the syntax {project}.mail.yaas.io, where {project} refers to the project on whose behalf you send the email.

To circumvent this restriction, you can register your own domain in the YaaS Verification Service and get it verified later. For more information about domain verification, see YaaS Verification Service.


Custom SMTP Server Integration

You can integrate the Email service with a custom SMTP server. When you configure the service to use a custom SMTP server, the Email service does not deliver emails directly, but instead uses SMTP to submit the emails to your configured server. The SMTP server acts as a Mail Transfer Agent (MTA), or more specifically, as a Mail Submission Agent (MSU), and is thus responsible for handling the delivery of the message.

When you use a custom SMTP server, your project is not restricted to specific fromAddress domains. However, the SMTP server itself can impose its own restrictions on how it handles email messages.

When you deliver emails with a custom SMTP server, YaaS does not scan emails or email attachments for malware. To protect the recipients of your emails, make sure you have proper security measures in place when using a custom SMTP server.

SMTP server configuration

Configure the integration of a custom SMTP server on a per-project level. Each integration affects all emails that the Email service sends on behalf of the specified project.

To configure a custom SMTP server, create the configuration properties shown in the Configuration service:

Property clientProperty keyDescriptionExample value
hybris.emailsmtp.hostThe host name or IP address of the SMTP server.smtp.example.net
hybris.emailsmtp.portThe port where the Email service connects to the SMTP server. If empty, the service derives the port from the smtp.security property. Port 465 for SSL and 587 for STARTTLS.465
hybris.emailsmtp.securityThe type of connection security the Email service uses for communication with the SMTP server. This value must be one of these:If empty, the value defaults to STARTTLS, unless you set the smtp.port value to port 465, which is the standard port for SMTP over SSL.
By design, the Email service does not support plain SMTP communication without connection security.
SSL
hybris.emailsmtp.usernameThe user name that the Email service uses to authenticate itself against the SMTP server.`me@domain.com`
hybris.emailsmtp.passwordThe password that the Email service uses to authenticate itself against the SMTP server. While you must provide the password in plain text, the Configuration service stores the password in an encrypted format by setting the secured flag for this property to true.mPa$wrt!

As indicated in the table, all configurations are stored in client-specific configuration properties that belong to hybris.email. To set these configuration properties, use the hybris.configuration_admin scope when calling the Configuration service.

To disable a custom SMTP server configuration at any time, and use the default Email service email sending functionality instead, you must remove all of the configuration properties listed in the table from the Configuration service.


Introduction to Tutorials

This tutorial demonstrates how to prepare and send emails using templates from the Velocity Template service. In this tutorial, you will send notification emails to contest winners using a fictional storefront called Virtually-4-Free as the basis for all examples shown.

The email template in this tutorial uses HTML formatting so that you can use your corporate design in the email. Over time, you will send similar emails to numerous winners. You don't want to do all the repetitive formatting work each time, but you do want to customize each email for the individual contest winners. The email should contain a personalized salutation, as well as the prize itself: a coupon that can be redeemed at your example shop.

Basic tutorials

The three sections of this tutorial focus on getting you started quickly. Perform them in the order indicated. They cover all the steps necessary to send the basic win-notification emails.

  1. Create your template files:

    The template file for the email contents is an HTML file that includes a few snippets of Velocity template code.

  2. Upload your email template:

    Because you use the Email service to create templates, you will upload any Velocity template files you create to the Email service.

  3. Send an email:

    When sending an email, specify which email template to use, add email addresses for the sender and recipient, and personalize the email contents by passing data into the template.

Advanced templating tutorials

The Velocity Template service provides several tutorials for more advanced templating topics. Perform them in the order indicated.

  1. Leverage Structured Data:

    Pass JSON data when sending emails, and process the data using Velocity directives and tools.

  2. Secure your templates:

    Use the Velocity Template Tool to sanitize your outputs and prevent cross-site scripting.

Prerequisites

You can execute all the steps in this tutorial using the API Console for the Email service and the API Console for the Velocity Template service. For more information about the API Console, see First Steps with APIs.

Specifically, you must know how to:

  1. Set up a project. See Getting Started Guide > Set Up a Project.
  2. Obtain an access token for an authenticated client of your project. See Getting Started Guide > Get an Access Token.
  3. Make API calls using that access token. See Getting Started Guide > Make a First API Call.

This tutorial uses the placeholders listed. You can replace these placeholders with values from your own project.

DetailPlaceholderExample Value
Project ID{project}virtually4free
Application or service's YaaS Client Identifier{client}hybris.order


Create Your Template

This tutorial shows you how to write the contents of the subject and body templates for your email templates.

Step 1: Prepare the template content for the email subject

In this use case, you want to send notification emails to the winners of the Virtually-4-Free storefront contest. The subject of the emails should be customizable for the individual winners. Use simple Velocity code in the template to customize the subject line.

To create the template content for the email subject, paste this text into a text editor:

Hello ${data.customerName}! You have won a coupon for the Virtually-4-Free shop

When the system sends the email using the Velocity template, it replaces the variable expression that serves as a placeholder for the customerName attribute with a value.

Prepend all attribute names with data, which is a hash array that the Email service uses to make the attributes available to Velocity. For details about how to work with attributes, see the Velocity Templates for the Email service section.

Save your file as subject.vm. The .vm suffix is the standard file extension for Velocity files. You can save the file to refer to it later, but you will upload only the contents of the file, and not the file itself.

Step 2: Prepare the template content for the email body

Because you will use HTML formatting for your notification emails, as indicated in the use case, you must use a template file that includes both HTML code and Velocity code.

To create the template content for the body of the email, paste this text into a text editor:

<html>
<body>
  <h1>Win notification!</h1>
  <p>Dear ${data.customerName},</p>
  <p>
     Thank you for participating in our super-fabulous new customer competition!
     You're one of the lucky winners!
  </p>
  <p>
    We hereby present you with your coupon worth
    <strong>${data.couponValue}</strong>,
    to make your next purchase at Virtually-4-Free shop even cheaper.
    To redeem your coupon, simply enter the following coupon code during checkout:
    <div class="coupon">${data.couponCode}<div>
  </p>
  <p>
    Or, start your next shopping spree from 
    <a href="https://virtually4free.example.net/coupon?code=${data.couponCode}">this link</a>,
    and have the coupon code conveniently pre-filled!
  </p>
</body>
</html>

In this template file, use the same customerName placeholder that you used in the subject template file. In addition, there are two new placeholders named couponValue and couponCode, also prepended by the data hash array.

The template file uses the couponCode attribute in both the visible contents of the HTML and in a hyperlink URL. You can refer to attributes anywhere in the HTML code of your template file. This gives you a great deal of flexibility and control when authoring your own template files for the Email service.

The great flexibility of templating can introduce security concerns. While the example body template file in this tutorial is suitable for your first experiments with the Email service, take care to ensure proper HTML formatting and prevent code-injection attacks for your production template files. For more information on this subject, see the advanced templating tutorial about securing your templates.

When you are done adjusting the template, save the file as body.vm. The next step is to upload your template to the Email service.


Upload Your Template

In the "Create Your Template" tutorial, you prepared content for your subject and body templates. Now it's time to upload them to the Velocity Template service. The content of the templates will upload as "variants" of a template, and the template will act as a container for those variants. You can upload your templates using either of these methods:

  • Create the template first, and then add one or more variants.
  • Directly create both the template and its first variant in one simplified call.

Provide this information when you create a new template:

  • The properties owner and code *Together, these properties identify the email template. You will refer to them in your email template later.
    * In this tutorial, the **owner** is the `{client}`, as described in the [introduction](/services/email/latest/index.html#preparations). If you do not specify **owner**, the system uses `{client}` as the default owner value.
    * The **code** of the email template is a short identifier that reflects the purpose of the email template. This example uses `win-notification` as the code.
    
  • The fields name and description
    • The optional fields are part of the user documentation of the email template and display in any template management user interface (UI).

In the steps that follow, use the API Console to define an email template, in the Email service, that uses the information you provide.

Step 1: Create the template (Optional)

Using the API Console, issue this request to the Velocity Template service:

  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/velocity-template/v1/{project}/templates
  • Content Type: application/json
  • Body:
    {
        "code" : "win-notification",
        "name" : "A notification email for contest winners",
        "description" : "An email template for emails to winners of our new customer contest. Includes a coupon."
    }
    

The request creates an empty email template containing all the required metadata associated with the template.

A successful response includes:

  • Status code: 201
  • Content Type: application/json
  • Body: The body content is the same as the request body.

Troubleshooting

If you receive a 400 response status code, verify that there are no typos in the JSON object that you sent. The object must be syntactically-correct JSON, and its structure must conform to the example shown. Look at the error message in the response body, which might help to identify the problem.

If you encounter authorization problems, verify that you are using a suitable access token. Also, verify that you replaced the {client} in your JSON with your actual Application or service's YaaS Client Identifier.

Step 2: Upload the Velocity template content for the subject

You created the email template, but it still does not contain any information about how the subject and body of the email should look. Upload this information in two steps. In this step, you upload the subject content. In the next step, you will upload the body content.

To upload the subject of the email, issue this request to the Velocity Template service:

  • Method: PUT
  • Request URL: https://api.beta.yaas.io/hybris/velocity-template/v1/{project}/{client}/templates/win-notification/variants/subject
  • Content Type: application/octet-stream
  • Body: The body content is the content of the subject.vm file created in the "Create Your Template" tutorial.

A successful response includes:

  • Status code: 200
  • Content type: application/json
  • Body example:
    {
        "sizeInBytes": 85,
        "type": "body",
        "url": "https://api.beta.yaas.io/hybris/velocity-template/v1/{project}/{client}/templates/win-notification/variants/subject"
    }
    
If you append ?validateTemplate=true to the Request URL, the content of the template variant passes through a validator. If there is a syntactic error in the template, the upload fails.

Step 3: Upload the Velocity template content for the body

To upload the template body content, issue this request:

  • Method: PUT
  • Request URL: https://api.beta.yaas.io/hybris/velocity-template/v1/{project}/{client}/templates/win-notification/variants/body
  • Content Type: application/octet-stream
  • Body: The content of the body.vm file created in the "Create Your Template" tutorial

A successful response includes:

  • Status code: 200
  • Content type: application/json
  • Body example:
    {
        "sizeInBytes": 749,
        "type": "body",
        "url": "https://api.beta.yaas.io/hybris/velocity-template/v1/{project}/{client}/templates/win-notification/variants/body"
    }
    

Troubleshooting

Make sure that you are using a suitable authorization token.

Be aware that even if you successfully upload a template file, the Velocity code might not be properly validated. This is because Velocity is often lenient when evaluating template files. If the system finds a syntactical error, the template file evaluation is likely to succeed anyway because Velocity simply outputs that part of the template, verbatim.

You can, however, append ?validateTemplate=true to the Request URL to pass the content of the template file through a validator. When you add the validation string, the upload fails if there is a syntactic error in the template.

Congratulations! You have created and uploaded your first template and you can now use it to send an email in the next tutorial.


Send an Email

This tutorial shows you how to make use of the templates that you wrote and uploaded in the "Upload Your Template" tutorial, and specifically, how to send notification emails. It also shows you how to pass custom values to defined attributes in order to personalize the contents of the email for the individual contest winner.

Currently, you can only use the Email service to send emails with a fromAddress that belongs to the domain {yourProjectId}.mail.yaas.io, where {yourProjectId} is the ID of your project. For example:

john.doe@{yourProjectId}.mail.yaas.io

To avoid the email domain restriction, and use your own domain in the fromAddress, refer to the Sending from your own Domain documentation.

When sending an email, you must provide additional inputs to the Email service. These inputs are explained in detail here.

You can use the API Console to send emails using these inputs.

Send an email

To send an email, issue this request to the Email service:

  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/email/v2/send
  • Content Type: application/json
  • Body:
    {
        "fromAddress" : "virtually4free@yaas.io",
        "fromName" : "Virtually 4 Free",
        "replyToAddress" : "virtually4freeSupport@yaas.io",
        "replyToName" : "Virtual Support",
        "toAddress" : "{the recipient's email address, such as your own}",
        "toName" : "John Doe",
        "subjectTemplate" : {
           "code" : "win-notification",
           "variant" : "subject",
           "attributes" : {
              "customerName" : "John Doe"
           }
        },
        "bodyTemplate" : {
           "code" : "win-notification",
           "variant" : "body",
           "attributes" : {
              "customerName" : "John Doe",
              "couponValue"  : "1000 EUR",
              "couponCode"   : "ACA114Hk"
           }
        }
    }
    

You can also add more recipients to your email:

  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/email/v2/send
  • Content Type: application/json
  • Body:
    {
        "fromAddress" : "virtually4free@yaas.io",
        "fromName" : "Virtually 4 Free",
        "replyToAddress" : "virtually4freeSupport@yaas.io",
        "replyToName" : "Virtual Support",
        "toAddress" : "{the valid recipient's email address, such as your own}",
        "toName" : "John Doe",
        "to" : [{
            "address" : "{second valid recipient's email address}",
            "name" : "John Doe"
        }],
        "cc" : [{
            "address" : "{the valid email of the notification center}",
            "name" : "Win Notification Center"
        }],
        "bcc" : [{
            "address" : "{the valid email of the notification tracking}",
            "name" : "Win Notification Tracking"
        }],
        "subjectTemplate" : {
           "code" : "win-notification",
           "variant" : "subject",
           "attributes" : {
              "customerName" : "John Doe"
           }
        },
        "bodyTemplate" : {
           "code" : "win-notification",
           "variant" : "body",
           "attributes" : {
              "customerName" : "John Doe",
              "couponValue"  : "1000 EUR",
              "couponCode"   : "ACA114Hk"
           }
        }
    }
    

Whether you include additional recipients or not, a successful response includes:

  • Status code: 201
  • Body: None

Troubleshooting

If you receive a 400 response status code, read the provided error message. Here are some common problems that you might need to fix if your send request yields an error response:

  • Verify that there are no typos in the JSON object that you sent. The object must be syntactically-correct JSON, and its structure must conform to the example shown. Look at the error message in the response body, which might help to identify the problem.

  • If you encounter authorization problems, verify that you are using a suitable access token. Also, verify that you replaced the {client} in your JSON with your actual Client.

  • Currently, you must set the domain of the fromAddress to {project}.mail.yaas.io, where {project} represents your actual YaaS project.

  • Make sure that the domain(s) of the toAddress, to, cc, and bcc addresses exist and are configured to receive emails. It is strongly recommended that you send test emails to your own addresses so that you can verify the results by looking for them in your inbox. Please do not use the Email service to send messages to other recipients without their prior consent – even for testing purposes.

  • Verify that the referenced email template is present and that it has a Velocity template variant for both the subject and the body. The owner and code must exactly match an existing email template. Both are case-sensitive.

  • The Velocity template variants for the subject and body must be syntactically-correct in terms of the Velocity Template Language (VCL). While VCL is very lenient about syntax, and usually falls back to rendering the source code verbatim, there are some constructs that might cause Velocity template rendering to fail completely. Read the Velocity user guide, or start from the Velocity templates in this guide, and modify them step-by-step to get to the root of any such problems.


Send an Email Using Template

This tutorial shows you how to make use of the templates that you wrote and uploaded in the "Upload Your Template" tutorial, and specifically, how to send notification emails. It also shows you how to pass custom values to defined attributes in order to personalize the contents of the email for the individual contest winner.

Currently, you can only use the Email service to send emails with a fromAddress that belongs to the domain {yourProjectId}.mail.yaas.io, where {yourProjectId} is the ID of your project. For example:

john.doe@{yourProjectId}.mail.yaas.io

To avoid the email domain restriction, and use your own domain in the fromAddress, refer to the Sending from your own Domain documentation.

When sending an email, you must provide additional inputs to the Email service. These inputs are explained in detail here.

You can use the API Console to send emails using these inputs.

Send an email

To send an email, issue this request to the Email service:

  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/email/v2/send
  • Content Type: application/json
  • Body:
    {
        "fromAddress" : "virtually4free@yaas.io",
        "fromName" : "Virtually 4 Free",
        "replyToAddress" : "virtually4freeSupport@yaas.io",
        "replyToName" : "Virtual Support",
        "toAddress" : "{the recipient's email address, such as your own}",
        "toName" : "John Doe",
        "subjectTemplate" : {
           "code" : "win-notification",
           "variant" : "subject",
           "attributes" : {
              "customerName" : "John Doe"
           }
        },
        "bodyTemplate" : {
           "code" : "win-notification",
           "variant" : "body",
           "attributes" : {
              "customerName" : "John Doe",
              "couponValue"  : "1000 EUR",
              "couponCode"   : "ACA114Hk"
           }
        }
    }
    

You can also add more recipients to your email:

  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/email/v2/send
  • Content Type: application/json
  • Body:
    {
        "fromAddress" : "virtually4free@yaas.io",
        "fromName" : "Virtually 4 Free",
        "replyToAddress" : "virtually4freeSupport@yaas.io",
        "replyToName" : "Virtual Support",
        "toAddress" : "{the valid recipient's email address, such as your own}",
        "toName" : "John Doe",
        "to" : [{
            "address" : "{second valid recipient's email address}",
            "name" : "John Doe"
        }],
        "cc" : [{
            "address" : "{the valid email of the notification center}",
            "name" : "Win Notification Center"
        }],
        "bcc" : [{
            "address" : "{the valid email of the notification tracking}",
            "name" : "Win Notification Tracking"
        }],
        "subjectTemplate" : {
           "code" : "win-notification",
           "variant" : "subject",
           "attributes" : {
              "customerName" : "John Doe"
           }
        },
        "bodyTemplate" : {
           "code" : "win-notification",
           "variant" : "body",
           "attributes" : {
              "customerName" : "John Doe",
              "couponValue"  : "1000 EUR",
              "couponCode"   : "ACA114Hk"
           }
        }
    }
    

Whether you include additional recipients or not, a successful response includes:

  • Status code: 201
  • Body: None

Code examples

The following are the Jersey and Spring MVC implementations of the example given above.

First we create the Email send request as a HashMap:

` Create email send request public static Map<String, Object> getEmailWithTemplateRequest() { Map<String, Object> attributes = new HashMap<>(); attributes.put("customerName", "John Doe"); attributes.put("couponValue", "1000 EUR"); attributes.put("couponCode", "ACA114Hk");

    Map<String, Object> subjectTemplateInfo = new HashMap<>();
    subjectTemplateInfo.put("code", "win-notification");
    subjectTemplateInfo.put("variant", "subject");
    subjectTemplateInfo.put("attributes", attributes);

    Map<String, Object> bodyTemplateInfo = new HashMap<>();
    bodyTemplateInfo.put("code", "win-notification");
    bodyTemplateInfo.put("variant", "body");
    bodyTemplateInfo.put("attributes", attributes);

    Map<String, Object> sendEmailRequest = new HashMap<>();
    sendEmailRequest.put("toAddress", "john.doe@yaastest.io");
    sendEmailRequest.put("toName", "John Doe");
    sendEmailRequest.put("fromAddress", "virtually4free@yaas.io");
    sendEmailRequest.put("fromName", "Virtually 4 Free");
    sendEmailRequest.put("subjectTemplate", subjectTemplateInfo);
    sendEmailRequest.put("bodyTemplate", bodyTemplateInfo);

    return sendEmailRequest;
}

#### Jersey implementation

You can use Jersey to issue the request to the Email Service:

``` Send using Jersey
    Map<String, Object> requestAsMap = getEmailWithTemplateRequest();

    //Use the payload in your request
    final Response response = client
        .target("https://api.beta.yaas.io/hybris/email/v2)
        .path("send")
        .request()
        .header(HttpHeaders.AUTHORIZATION, "Bearer " + validAccessToken)
        .post(Entity.json(requestAsMap));

Spring implementation

If you do not use Jersey, you might be interested in the Spring implementation shown here. It uses the classes from the org.springframework package's subpackages.

` Send using Spring Map<String, Object> requestAsMap = getEmailWithTemplateRequest();

final HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + validAccessToken);
headers.setContentType(MediaType.APPLICATION_JSON);

final HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestAsMap, headers);
final URI serviceUri = UriComponentsBuilder.fromHttpUrl("https://api.beta.yaas.io/hybris/email/v2).pathSegment("send").build().encode().toUri();
final ResponseEntity<String> response = new RestTemplate().exchange(serviceUri, HttpMethod.POST, requestEntity, String.class);

`

Troubleshooting

If you receive a 400 response status code, read the provided error message. Here are some common problems that you might need to fix if your send request yields an error response:

  • Verify that there are no typos in the JSON object that you sent. The object must be syntactically-correct JSON, and its structure must conform to the example shown. Look at the error message in the response body, which might help to identify the problem.

  • If you encounter authorization problems, verify that you are using a suitable access token. Also, verify that you replaced the {client} in your JSON with your actual Client.

  • Currently, you must set the domain of the fromAddress to {project}.mail.yaas.io, where {project} represents your actual YaaS project.

  • Make sure that the domain(s) of the toAddress, to, cc, and bcc addresses exist and are configured to receive emails. It is strongly recommended that you send test emails to your own addresses so that you can verify the results by looking for them in your inbox. Please do not use the Email service to send messages to other recipients without their prior consent – even for testing purposes.

  • Verify that the referenced email template is present and that it has a Velocity template variant for both the subject and the body. The owner and code must exactly match an existing email template. Both are case-sensitive.

  • The Velocity template variants for the subject and body must be syntactically-correct in terms of the Velocity Template Language (VCL). While VCL is very lenient about syntax, and usually falls back to rendering the source code verbatim, there are some constructs that might cause Velocity template rendering to fail completely. Read the Velocity user guide, or start from the Velocity templates in this guide, and modify them step-by-step to get to the root of any such problems.


  • Send feedback

    If you find any information that is unclear or incorrect, please let us know so that we can improve the Dev Portal content.

  • Get Help

    Use our private help channel. Receive updates over email and contact our specialists directly.

  • hybris Experts

    If you need more information about this topic, visit hybris Experts to post your own question and interact with our community and experts.