Examples by language¶
Every example sends the same message and reads the key from the FRONTENGINE_KEY environment variable. None of them uses a FrontEngine library: the API is an HTTPS call with JSON.
Before you start¶
| Item | Value |
|---|---|
| Method and URL | POST https://api.frontengine.net/api/v1/send/message |
| Authentication | X-Server-API-Key header |
| Body | JSON, with Content-Type: application/json |
| Sender | an address on a domain verified for your server |
Body fields:
| Field | Type | Note |
|---|---|---|
to, cc, bcc | list of addresses | Up to 50 addresses in each field. At least one recipient in total |
from | string | Required. Accepts Name <address@domain> |
sender | string | Optional |
reply_to | string | Optional |
subject | string | Subject |
plain_body, html_body | string | At least one of the two |
tag | string | Optional. One tag per message, returned in events |
headers | object | Additional headers, such as {"X-Order": "1234"} |
attachments | list | Each item has name, content_type and data (content in Base64) |
Check the status field
The API answers HTTP 200 even when it refuses the send over an authentication or validation error. The result is in the status field of the JSON: success, error or parameter-error. An HTTP code other than 200, such as 503, means a temporary failure on our side: try again after a few seconds.
Success answer:
{
"status": "success",
"time": 0.042,
"flags": {},
"data": {
"message_id": "[email protected]",
"messages": {
"[email protected]": { "id": 1042, "token": "Zp3kQ9xT" }
}
}
}
Error answer:
{
"status": "error",
"time": 0.003,
"flags": {},
"data": {
"code": "UnauthenticatedFromAddress",
"message": "The From address is not authorised to send mail from this server"
}
}
Sending with the API¶
curl -sS https://api.frontengine.net/api/v1/send/message \
-H "X-Server-API-Key: $FRONTENGINE_KEY" \
-H "Content-Type: application/json" \
-d '{
"from": "My Store <[email protected]>",
"to": ["[email protected]"],
"subject": "Your order is confirmed",
"plain_body": "We received your order 1234.",
"html_body": "<p>We received your order <strong>1234</strong>.</p>",
"tag": "order"
}'
# pip install requests
import os
import requests
response = requests.post(
"https://api.frontengine.net/api/v1/send/message",
headers={"X-Server-API-Key": os.environ["FRONTENGINE_KEY"]},
json={
"from": "My Store <[email protected]>",
"to": ["[email protected]"],
"subject": "Your order is confirmed",
"plain_body": "We received your order 1234.",
"html_body": "<p>We received your order <strong>1234</strong>.</p>",
"tag": "order",
},
timeout=30,
)
response.raise_for_status() # other than 200: temporary failure, try again
body = response.json()
if body["status"] != "success":
raise RuntimeError(f"{body['data'].get('code')}: {body['data'].get('message')}")
print(body["data"]["messages"])
// send.mjs, Node.js 18 or later
const response = await fetch("https://api.frontengine.net/api/v1/send/message", {
method: "POST",
headers: {
"X-Server-API-Key": process.env.FRONTENGINE_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "My Store <[email protected]>",
to: ["[email protected]"],
subject: "Your order is confirmed",
plain_body: "We received your order 1234.",
html_body: "<p>We received your order <strong>1234</strong>.</p>",
tag: "order",
}),
});
if (!response.ok) {
// other than 200: temporary failure, try again
throw new Error(`HTTP ${response.status}`);
}
const body = await response.json();
if (body.status !== "success") {
throw new Error(`${body.data.code}: ${body.data.message}`);
}
console.log(body.data.messages);
<?php
$payload = json_encode([
'from' => 'My Store <[email protected]>',
'to' => ['[email protected]'],
'subject' => 'Your order is confirmed',
'plain_body' => 'We received your order 1234.',
'html_body' => '<p>We received your order <strong>1234</strong>.</p>',
'tag' => 'order',
]);
$ch = curl_init('https://api.frontengine.net/api/v1/send/message');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'X-Server-API-Key: ' . getenv('FRONTENGINE_KEY'),
'Content-Type: application/json',
],
]);
$raw = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($raw === false || $http !== 200) {
// other than 200: temporary failure, try again
throw new RuntimeException("HTTP $http");
}
$body = json_decode($raw, true);
if ($body['status'] !== 'success') {
throw new RuntimeException(($body['data']['code'] ?? '') . ': ' . ($body['data']['message'] ?? ''));
}
print_r($body['data']['messages']);
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
type result struct {
Status string `json:"status"`
Data struct {
Code string `json:"code"`
Message string `json:"message"`
Messages map[string]struct {
ID int64 `json:"id"`
Token string `json:"token"`
} `json:"messages"`
} `json:"data"`
}
func main() {
payload, _ := json.Marshal(map[string]any{
"from": "My Store <[email protected]>",
"to": []string{"[email protected]"},
"subject": "Your order is confirmed",
"plain_body": "We received your order 1234.",
"html_body": "<p>We received your order <strong>1234</strong>.</p>",
"tag": "order",
})
req, err := http.NewRequest(http.MethodPost, "https://api.frontengine.net/api/v1/send/message", bytes.NewReader(payload))
if err != nil {
log.Fatal(err)
}
req.Header.Set("X-Server-API-Key", os.Getenv("FRONTENGINE_KEY"))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// other than 200: temporary failure, try again
log.Fatalf("HTTP %d", resp.StatusCode)
}
var body result
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
log.Fatal(err)
}
if body.Status != "success" {
log.Fatalf("%s: %s", body.Data.Code, body.Data.Message)
}
fmt.Println(body.Data.Messages)
}
// Java 15 or later
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Send {
public static void main(String[] args) throws Exception {
String payload = """
{
"from": "My Store <[email protected]>",
"to": ["[email protected]"],
"subject": "Your order is confirmed",
"plain_body": "We received your order 1234.",
"html_body": "<p>We received your order <strong>1234</strong>.</p>",
"tag": "order"
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.frontengine.net/api/v1/send/message"))
.timeout(Duration.ofSeconds(30))
.header("X-Server-API-Key", System.getenv("FRONTENGINE_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
// other than 200: temporary failure, try again
throw new IllegalStateException("HTTP " + response.statusCode());
}
// Parse the JSON with your library (Jackson, Gson) and check the "status" field.
System.out.println(response.body());
}
}
// .NET 6 or later
using System.Net.Http.Json;
using System.Text.Json;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
client.DefaultRequestHeaders.Add(
"X-Server-API-Key", Environment.GetEnvironmentVariable("FRONTENGINE_KEY"));
var response = await client.PostAsJsonAsync("https://api.frontengine.net/api/v1/send/message", new
{
from = "My Store <[email protected]>",
to = new[] { "[email protected]" },
subject = "Your order is confirmed",
plain_body = "We received your order 1234.",
html_body = "<p>We received your order <strong>1234</strong>.</p>",
tag = "order",
});
// other than 200: temporary failure, try again
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<JsonElement>();
if (body.GetProperty("status").GetString() != "success")
{
throw new InvalidOperationException(body.GetProperty("data").ToString());
}
Console.WriteLine(body.GetProperty("data").GetProperty("messages"));
require "json"
require "net/http"
require "uri"
uri = URI("https://api.frontengine.net/api/v1/send/message")
request = Net::HTTP::Post.new(uri)
request["X-Server-API-Key"] = ENV.fetch("FRONTENGINE_KEY")
request["Content-Type"] = "application/json"
request.body = {
from: "My Store <[email protected]>",
to: ["[email protected]"],
subject: "Your order is confirmed",
plain_body: "We received your order 1234.",
html_body: "<p>We received your order <strong>1234</strong>.</p>",
tag: "order"
}.to_json
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 30) do |http|
http.request(request)
end
# other than 200: temporary failure, try again
raise "HTTP #{response.code}" unless response.code == "200"
body = JSON.parse(response.body)
raise "#{body['data']['code']}: #{body['data']['message']}" unless body["status"] == "success"
puts body["data"]["messages"]
Attachments¶
The content of each attachment goes in Base64 in the data field. The assembled message, with its attachments, is subject to the 50 MB limit. Base64 encoding increases the file size by about a third.
curl -sS https://api.frontengine.net/api/v1/send/message \
-H "X-Server-API-Key: $FRONTENGINE_KEY" \
-H "Content-Type: application/json" \
-d '{
"from": "My Store <[email protected]>",
"to": ["[email protected]"],
"subject": "Your invoice",
"plain_body": "The invoice for order 1234 is attached.",
"attachments": [
{
"name": "invoice-1234.pdf",
"content_type": "application/pdf",
"data": "'"$(base64 -w0 invoice-1234.pdf)"'"
}
]
}'
import base64
import os
import requests
with open("invoice-1234.pdf", "rb") as f:
data = base64.b64encode(f.read()).decode("ascii")
response = requests.post(
"https://api.frontengine.net/api/v1/send/message",
headers={"X-Server-API-Key": os.environ["FRONTENGINE_KEY"]},
json={
"from": "My Store <[email protected]>",
"to": ["[email protected]"],
"subject": "Your invoice",
"plain_body": "The invoice for order 1234 is attached.",
"attachments": [
{"name": "invoice-1234.pdf", "content_type": "application/pdf", "data": data}
],
},
timeout=60,
)
response.raise_for_status()
print(response.json()["status"])
Sending with SMTP¶
| Item | Value |
|---|---|
| Host | smtp-out.frontengine.net |
| Port | 587 with STARTTLS, or 465 with implicit TLS |
| Authentication | AUTH PLAIN or AUTH LOGIN |
| Username | any text. The examples use frontengine |
| Password | the server key |
import os
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "My Store <[email protected]>"
msg["To"] = "[email protected]"
msg["Subject"] = "Your order is confirmed"
msg.set_content("We received your order 1234.")
msg.add_alternative("<p>We received your order <strong>1234</strong>.</p>", subtype="html")
with smtplib.SMTP("smtp-out.frontengine.net", 587, timeout=30) as smtp:
smtp.starttls()
smtp.login("frontengine", os.environ["FRONTENGINE_KEY"])
smtp.send_message(msg)
// npm install nodemailer
import nodemailer from "nodemailer";
const transport = nodemailer.createTransport({
host: "smtp-out.frontengine.net",
port: 587,
secure: false, // STARTTLS
requireTLS: true,
auth: { user: "frontengine", pass: process.env.FRONTENGINE_KEY },
});
const info = await transport.sendMail({
from: "My Store <[email protected]>",
to: "[email protected]",
subject: "Your order is confirmed",
text: "We received your order 1234.",
html: "<p>We received your order <strong>1234</strong>.</p>",
});
console.log(info.response);
To use port 465, replace smtplib.SMTP with smtplib.SMTP_SSL and remove starttls() in Python. In Nodemailer, use port: 465 and secure: true.
Tag over SMTP
To tag a message when sending over SMTP, add the header X-Postal-Tag: order. It has the same effect as the API's tag field.
Common errors¶
code | Cause | What to do |
|---|---|---|
AccessDenied | X-Server-API-Key header missing | Send the header |
InvalidServerAPIKey | Wrong or disabled key | Check the environment variable and the credential |
ServerSuspended | Server suspended | Talk to support |
UnauthenticatedFromAddress | The from domain is not verified for this server | Check the sending domain |
NoRecipients, NoContent, FromAddressMissing | Required field missing | Fix the request |
TooManyToAddresses, TooManyCCAddresses, TooManyBCCAddresses | More than 50 addresses in the field | Split into more than one request |
AttachmentMissingName, AttachmentMissingData | Attachment without name, or with data empty or not Base64 | Fix the attachment |
MessageRejected | The message was refused permanently. The message field carries the reason | Fix according to the reason |
The full list is in Errors.