Email Notifications
The Email Notifications API allows you to send emails to your users programmatically. You can send both custom-formatted emails and template-based emails using SendGrid templates.
Supported Features
- Send custom emails with HTML and plain text content
- Include file attachments
- Use SendGrid templates with dynamic data
- Customize sender name and email address
- Track delivery through response codes
Prerequisites
To use the Email Notifications API, you need:
- A valid API subscription key
- Authorization to access the notification endpoints
- Valid sender email addresses configured in your account
Sending a Standard Email
Endpoint
POST /EmailNotification/SendNotification
Request Headers
Header | Description |
---|---|
correlationid | Unique identifier for tracking the request |
x-ls-party-id | Party identifier for the sender |
Ocp-Apim-Subscription-Key | Your API subscription key |
Request Body
{
"subject": "Your Account Update",
"plainTextContent": "Your account has been updated successfully.",
"htmlContent": "<h1>Account Update</h1><p>Your account has been <strong>updated</strong> successfully.</p>",
"to": "recipient@example.com",
"recipientName": "John Doe",
"from": "noreply@yourcompany.com",
"fromName": "Your Company",
"attachments": [
{
"content": "base64encodedcontent",
"type": "application/pdf",
"filename": "receipt.pdf",
"disposition": "attachment",
"contentId": "receipt-123"
}
]
}
Using SendGrid Templates
SendGrid templates allow you to create reusable email templates with dynamic content placeholders.
Endpoint
POST /EmailNotification/SendSendGridEmailTemplate
Request Headers
Same as standard email endpoint.
Request Body
{
"from": "noreply@yourcompany.com",
"fromName": "Your Company",
"recipients": [
"recipient@example.com"
],
"templateId": "d-f3ecde774f944a9e8a7a57848aecc4b7",
"templateData": {
"user_name": "John",
"reset_link": "https://example.com/reset/abc123",
"company_name": "Your Company"
}
}
Implementation Examples
- C#
- Java
- Python
- JavaScript
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class EmailService
{
private readonly HttpClient _client;
private readonly string _apiKey;
private readonly string _baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
public EmailService(string apiKey)
{
_apiKey = apiKey;
_client = new HttpClient();
_client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _apiKey);
}
public async Task<bool> SendEmailAsync(string to, string subject, string htmlContent)
{
var endpoint = $"{_baseUrl}/EmailNotification/SendNotification";
var request = new
{
subject = subject,
htmlContent = htmlContent,
plainTextContent = StripHtml(htmlContent),
to = to,
from = "noreply@yourcompany.com",
fromName = "Your Company"
};
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
_client.DefaultRequestHeaders.Add("correlationid", Guid.NewGuid().ToString());
var response = await _client.PostAsync(endpoint, content);
return response.IsSuccessStatusCode;
}
private string StripHtml(string html)
{
// Simple HTML stripping implementation
return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", "");
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;
import org.json.JSONObject;
public class EmailService {
private final HttpClient client;
private final String apiKey;
private final String baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
public EmailService(String apiKey) {
this.apiKey = apiKey;
this.client = HttpClient.newHttpClient();
}
public boolean sendEmail(String to, String subject, String htmlContent) throws Exception {
String endpoint = baseUrl + "/EmailNotification/SendNotification";
JSONObject request = new JSONObject();
request.put("subject", subject);
request.put("htmlContent", htmlContent);
request.put("plainTextContent", stripHtml(htmlContent));
request.put("to", to);
request.put("from", "noreply@yourcompany.com");
request.put("fromName", "Your Company");
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", apiKey)
.header("correlationid", UUID.randomUUID().toString())
.POST(HttpRequest.BodyPublishers.ofString(request.toString()))
.build();
HttpResponse<String> response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
return response.statusCode() == 200;
}
private String stripHtml(String html) {
// Simple HTML stripping implementation
return html.replaceAll("<[^>]*>", "");
}
}
import requests
import uuid
import re
class EmailService:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1"
def send_email(self, to, subject, html_content):
endpoint = f"{self.base_url}/EmailNotification/SendNotification"
headers = {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": self.api_key,
"correlationid": str(uuid.uuid4())
}
payload = {
"subject": subject,
"htmlContent": html_content,
"plainTextContent": self._strip_html(html_content),
"to": to,
"from": "noreply@yourcompany.com",
"fromName": "Your Company"
}
response = requests.post(endpoint, headers=headers, json=payload)
return response.status_code == 200
def _strip_html(self, html):
# Simple HTML stripping implementation
return re.sub('<[^<]+?>', '', html)
class EmailService {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1';
}
async sendEmail(to, subject, htmlContent) {
const endpoint = `${this.baseUrl}/EmailNotification/SendNotification`;
const headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': this.apiKey,
'correlationid': crypto.randomUUID()
};
const payload = {
subject,
htmlContent,
plainTextContent: this.stripHtml(htmlContent),
to,
from: 'noreply@yourcompany.com',
fromName: 'Your Company'
};
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(payload)
});
return response.ok;
}
stripHtml(html) {
// Simple HTML stripping implementation
return html.replace(/<[^>]*>/g, '');
}
}
Working with Attachments
To include attachments in your email, encode the file content in base64 and add it to the attachments array:
"attachments": [
{
"content": "JVBERi0xLjMNJeLjz9MNCjMgMCBvYmoNPDwgL0ZpbHRlciAvRmxhdGVEZWNvZGUg...",
"type": "application/pdf",
"filename": "report.pdf",
"disposition": "attachment",
"contentId": "report-id-123"
}
]
Best Practices
- Always include both HTML and plain text versions of your email
- Keep email size under 10MB including attachments
- Use SendGrid templates for consistent branding and easier management
- Test your emails across different clients and devices
- Include appropriate unsubscribe links in marketing emails
- Store the correlation ID for troubleshooting
Error Handling
The API returns standard HTTP status codes. Common errors include:
- 400 Bad Request: Invalid email format or missing required fields
- 401 Unauthorized: Invalid API key
- 429 Too Many Requests: Rate limit exceeded
- 500 Internal Server Error: Server-side issue
Always implement proper error handling and retry logic for production applications.
Was this page useful?