Use just one API to send Email, SMS, Fax and Voice Calls -
If you don't have an account, head to https://www.tnz.co.nz/Customer/SignUp/ and register.
To access the API, you'll need a User with API access:
The API v2.02 uses JWT token Authentication. Contact your TNZ Representative for OAuth2 authentication.
You can use one Auth Token for multiple use-cases, using the SubAccount and Department values to track reporting and billing.
This flexible API allows you to send multiple message types. For a brief overview of the API, see the TNZ API Structure guide.
https://api.tnz.co.nz/api/[Version]/[Action]/[MessageType]
[Version]
is the API Version ('v2.02')[Action]
defines the module ('send' a message or 'get' a status)[MessageType]
is the type of message ('email', 'sms', 'fax', etc.)The HTTP Headers define the API call's formatting -
> Headers for JSON formatted calls:
Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Auth Token]"
** The 'Accept' header is optional but encouraged
> Headers for XML formatted calls:
Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Auth Token]"
** Both 'Content-Type' and 'Accept' headers are mandatory
An example for sending an outbound SMS using Raw JSON -
URL:
- https://api.tnz.co.nz/api/v2.02/send/sms
Headers:
- Content-Type="application/json; encoding='utf-8'"
- Accept="application/json; encoding='utf-8'"
- Authorization="Basic eyJ0eXA....436k0-E4"
Data:
{
"MessageData" : {
"Message": "Hello, this is a test.",
"Destinations" : [ { "Recipient": "+6421000001" } ]
}
}
Possible HTTP status values are:
200 OK
- Message Accepted400 BAD REQUEST
- Invalid Variables401 Unauthorized
- Invalid Auth Token500 Internal Server Error
- API Server FaultAn example JSON response value:
{
"Result": "%STATUS%",
"MessageID": "%MESSAGEID%"
}
Status
- 'Success' or 'Failed' refers to your API POST result (explains whether your POST was accepted by our server). This is not your message's delivery result - to track message delivery, see API - Status Reporting.MessageID
- A message tracking identifier (maximum 40 characters, alphanumeric). If you do not supply this field in your submitted MessageData, the API will return one for you in the response body (UUID v4 of 36 characters).Note
- The API will verify that required fields are supplied, however it will not validate data. See TNZ API Errors for error descriptions.Find instructions for each Message Type:
HTTP Method: POST
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
{
"MessageData" :
{
"EmailSubject": "Test Email Subject",
"MessagePlain": "Hello, This is a test message. Thank you.",
"Destinations" :
[
{ "Recipient": "recipient.one@example.com" },
{ "Recipient": "recipient.two@example.com" },
]
}
}
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
{
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"EmailSubject": "Test Email Subject",
"SMTPFrom": "noreply@example.com",
"From": "noreply",
"FromEmail": "noreply@example.com",
"ReplyTo": "reply@example.com",
"MessagePlain": "Hello,\r\nThis is a test message.\r\nThank you.",
"MessageHTML": "<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>",
"Destinations" :
[
{
"Recipient": "john.doe@example.com",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "recipient.two@example.com", "Attention": "Recipient2" },
{ "Recipient": "recipient.three@example.com" },
{ "Recipient": "recipient.four@example.com" }
],
"Files":
[
{
"Name": "Sample1.pdf",
"Data": "%%BASE-64 CONTENT%%"
},
{
"Name": "Sample2.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/email \
--header "Content-Type: application/json; encoding='utf-8'" \
--header "Accept: application/json; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '{
"MessageData" :
{
"EmailSubject": "Test Email Subject",
"MessagePlain": "Hello, This is a test message. Thank you.",
"Destinations" :
[
{ "Recipient": "recipient.one@example.com" },
{ "Recipient": "recipient.two@example.com" },
]
}
}'
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/email \
--header "Content-Type: application/json; encoding='utf-8'" \
--header "Accept: application/json; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '{
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"EmailSubject": "Test Email Subject",
"SMTPFrom": "noreply@example.com",
"From": "noreply",
"FromEmail": "noreply@example.com",
"ReplyTo": "reply@example.com",
"MessagePlain": "Hello,\r\nThis is a test message.\r\nThank you.",
"MessageHTML": "<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>",
"Destinations" :
[
{
"Recipient": "john.doe@example.com",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "recipient.two@example.com" },
{ "Recipient": "recipient.three@example.com" },
{ "Recipient": "recipient.four@example.com" }
],
"Files":
[
{
"Name": "Sample1.pdf",
"Data": "%%BASE-64 CONTENT%%"
},
{
"Name": "Sample2.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}'
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
$authToken = "[Your Auth Token]";
$data = array(
"MessageData" => array(
"EmailSubject" => "Test Email Subject",
"MessagePlain" => "Hello, This is a test message. Thank you.",
"Destinations" => array(
array(
"Recipient" => "recipient.one@example.com"
),
array(
"Recipient" => "recipient.two@example.com"
),
),
)
);
$headers = array(
"Content-Type: application/json",
"Accept: application/json",
"encoding='utf-8'",
"Content-length: ".strlen(json_encode($data)),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/email");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header('Content-Type: application/json');
echo $response;
break;
case "400": // error
case "401": // unauthorized
header('Content-Type: application/json');
echo $response;
break;
case "500": // critical error
echo $response;
echo $err;
break;
default:
echo $response;
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
function GetBase64Contents($file_name)
{
// returns base64 encoded file data
if( file_exists($file_name) )
{
$fp = fopen($file_name,"r");
$file_content = fread($fp,filesize($file_name));
fclose($fp);
return base64_encode($file_content);
}
}
$authToken = "[Your Auth Token]";
$message_id = "ID123456"; //optional
$file1 = "[File Location]/Sample1.pdf";
$file2 = "[File Location]/Sample2.pdf";
$data = array(
"Sender" => $sender,
"APIKey" => $apikey,
"MessageData" => array(
"MessageID" => $message_id,
"Reference" => "Test1",
"WebhookCallbackURL" => "https://www.example.com/webhook",
"WebhookCallbackFormat" => "JSON",
"SendTime" => "2022-08-01T09:00:00",
"TimeZone" => "New Zealand",
"SubAccount" => "SubAccount01",
"Department" => "Department01",
"ChargeCode" => "BillingGroup01",
"EmailSubject" => "Test Email Subject",
"SMTPFrom" => "noreply@example.com",
"From" => "noreply",
"FromEmail" => "noreply@example.com",
"ReplyTo" => "reply@example.com",
"MessagePlain" => "Hello,\r\nThis is a test message.\r\nThank you.",
"MessageHTML" => "Hello,
This is a test message.
Thank you.",
"Destinations" => array(
array(
"Recipient" => "john.doe@example.com",
"Attention" => "John Doe",
"First Name" => "John",
"Last Name" => "Doe",
"Company" => "Example Corp",
"Custom1" => "",
"Custom2" => ""
),
array( "Recipient" => "recipient.two@example.com" ),
array( "Recipient" => "recipient.three@example.com" ),
array( "Recipient" => "recipient.four@example.com" )
),
"Files" => array(
array(
"Name" => basename($file1),
"Data" => GetBase64Contents($file1)
),
array(
"Name" => basename($file2),
"Data" => GetBase64Contents($file2)
)
),
)
);
$headers = array(
"Content-Type: application/json",
"Accept: application/json",
"encoding='utf-8'",
"Content-length: ".strlen(json_encode($data)),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/email");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header('Content-Type: application/json');
echo $response;
break;
case "400": // error
case "401": // unauthorized
header('Content-Type: application/json');
echo $response;
break;
case "500": // critical error
echo $response;
echo $err;
break;
default:
echo $response;
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Net;
using System.Text;
namespace TNZ
{
class Program
{
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/email";
string authToken = "[Your Auth Token]";
//
// Build JSON Data
//
string strJSONData = $@"{{
""MessageData"": {{
""EmailSubject"": ""Test Email Subject"",
""MessagePlain"": ""Hello, This is a test message. Thank you."",
""Destinations"":
[
{{ ""Recipient"": ""recipient.one@example.com"" }},
{{ ""Recipient"": ""recipient.two@example.com"" }},
]
}}
}}";
//
// Send HTTP Request to TNZ Rest API
//
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json; encoding='utf-8'";
request.Accept = "application/json; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(strJSONData);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream(); //open connection
stream.Write(byteArray, 0, byteArray.Length); // Send the data.
stream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Net;
using System.Text;
namespace TNZ
{
class Program
{
private static string GetFileContents(string strFileLocation)
{
//
// Read files in bytes, convert to Base64String and return in string
//
using (FileStream reader = new FileStream(strFileLocation, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
string strContent = Convert.ToBase64String(buffer);
ASCIIEncoding encoding = new ASCIIEncoding();
return Encoding.ASCII.GetString(encoding.GetBytes(strContent));
}
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/email";
string authToken = "[Your Auth Token]";
string file1 = "[File Location]/Sample1.pdf";
string file2 = "[File Location]/Sample2.pdf";
string file1_data = GetFileContents(file1);
string file2_data = GetFileContents(file2);
//
// Build JSON Data
//
string strJSONData = $@"{{
""MessageData"": {{
""MessageID"": ""ID123456"",
""Reference"": ""Test1"",
""WebhookCallbackURL"":""https://www.example.com/webhook"",
""WebhookCallbackFormat"":""JSON"",
""SendTime"": ""2022-08-01T09:00:00"",
""TimeZone"": ""New Zealand"",
""SubAccount"": ""SubAccount01"",
""Department"": ""Department01"",
""ChargeCode"": ""BillingGroup01"",
""EmailSubject"": ""Test Email Subject"",
""SMTPFrom"": ""noreply@example.com"",
""From"": ""noreply"",
""FromEmail"": ""noreply@example.com"",
""ReplyTo"": ""reply@example.com"",
""MessagePlain"": ""Hello,\r\nThis is a test message.\r\nThank you."",
""MessageHTML"": ""<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>"",
""Destinations"":
[
{{
""Recipient"": ""john.doe@example.com"",
""Attention"": ""John Doe"",
""First Name"": ""John"",
""Last Name"": ""Doe"",
""Company"": ""Example Corp""
}},
{{ ""Recipient"": ""recipient.two@example.com"", ""Attention"": ""Recipient 2"" }},
{{ ""Recipient"": ""recipient.three@example.com"" }},
{{ ""Recipient"": ""recipient.four@example.com"" }}
],
""Files"":
[
{{
""Name"": ""Sample1.pdf"",
""Data"": ""{file1_data}""
}},
{{
""Name"": ""Sample2.pdf"",
""Data"": ""{file2_data}""
}}
]
}}
}}";
//
// Send HTTP Request to TNZ Rest API
//
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json; encoding='utf-8'";
request.Accept = "application/json; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(strJSONData);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream(); //open connection
stream.Write(byteArray, 0, byteArray.Length); // Send the data.
stream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import json
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/email"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
data = {
"MessageData" :
{
"EmailSubject" : "Test Email Subject",
"MessagePlain" : "Hello, This is a test message. Thank you.",
"Destinations" :
[
{ "Recipient": "recipient.one@example.com" },
{ "Recipient": "recipient.two@example.com" }
]
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
print(r.text)
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import base64
import json
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/email"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
file_data = base64.b64encode(open("[File Location]/Sample1.pdf","rb").read()).decode("utf-8")
data = {
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"EmailSubject": "Test Email Subject",
"SMTPFrom": "noreply@example.com",
"From": "noreply",
"FromEmail": "noreply@example.com",
"ReplyTo": "reply@example.com",
"MessagePlain": "Hello,\r\nThis is a test message.\r\nThank you.",
"MessageHTML": "<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>",
"Destinations" :
[
{
"Recipient": "john.doe@example.com",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "recipient.two@example.com" },
{ "Recipient": "recipient.three@example.com" },
{ "Recipient": "recipient.four@example.com" }
],
"Files" :
[
{
"Name": "Sample1.pdf",
"Data": file_data
}
]
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
print(r.text)
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"ErrorMessage": [
"Missing or empty sender",
"Invalid sender format"
]
}
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?xml version="1.0" encoding="UTF-8"?>
<EmailRequest>
<MessageData>
<EmailSubject>Test Email Subject</EmailSubject>
<MessagePlain>Hello, This is a test message. Thank you.</MessagePlain>
<Destinations>
<Destination><Recipient>recipient.one@example.com</Recipient></Destination>
<Destination><Recipient>recipient.two@example.com</Recipient></Destination>
</Destinations>
</MessageData>
</EmailRequest>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?xml version="1.0" encoding="UTF-8"?>
<EmailRequest>
<MessageData>
<MessageID>ID123456</MessageID>
<Reference>Test1</Reference>
<WebhookCallbackURL>https://www.example.com/webhook</Reference>
<WebhookCallbackFormat>XML</Reference>
<SendTime>2022-08-01T09:00:00</SendTime>
<TimeZone>New Zealand</TimeZone>
<SubAccount>SubAccount01</SubAccount>
<Department>Department01</Department>
<ChargeCode>BillingGroup01</ChargeCode>
<EmailSubject>Test Email Subject</EmailSubject>
<SMTPFrom>noreply@example.com</SMTPFrom>
<From>noreply</From>
<FromEmail>noreply</FromEmail>
<ReplyTo>reply@example.com</ReplyTo>
<MessagePlain>Hello,\r\nThis is a test message.\r\nThank you.</MessagePlain>
<MessageHTML><![CDATA[<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>]]></MessageHTML>
<Destinations>
<Destination>
<Recipient>john.doe@example.com</Recipient>
<Attention>John Doe</Attention>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Company>Example Corp</Company>
<Custom1></Custom1>
<Custom2></Custom2>
</Destination>
<Destination><Recipient>recipient.two@example.com</Recipient></Destination>
<Destination><Recipient>recipient.three@example.com</Recipient></Destination>
<Destination><Recipient>recipient.four@example.com</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
<File>
<Name>Sample2.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</EmailRequest>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/email \
--header "Content-Type: application/xml; encoding='utf-8'" \
--header "Accept: application/xml; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '<?xml version="1.0" encoding="UTF-8"?>
<EmailRequest>
<MessageData>
<EmailSubject>Test Email Subject</EmailSubject>
<MessagePlain>Hello, This is a test message. Thank you.</MessagePlain>
<Destinations>
<Destination><Recipient>recipient.one@example.com</Recipient></Destination>
<Destination><Recipient>recipient.two@example.com</Recipient></Destination>
</Destinations>
</MessageData>
</EmailRequest>'
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/email \
--header "Content-Type: application/xml; encoding='utf-8'" \
--header "Accept: application/xml; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '<?xml version="1.0" encoding="UTF-8"?>
<EmailRequest>
<MessageData>
<MessageID>ID123456</MessageID>
<Reference>Test1</Reference>
<WebhookCallbackURL>https://www.example.com/webhook</WebhookCallbackURL>
<WebhookCallbackFormat>XML</WebhookCallbackFormat>
<SendTime>2022-08-01T09:00:00</SendTime>
<TimeZone>New Zealand</TimeZone>
<SubAccount>SubAccount01</SubAccount>
<Department>Department01</Department>
<ChargeCode>BillingGroup01</ChargeCode>
<EmailSubject>Test Email Subject</EmailSubject>
<SMTPFrom>noreply@domain.com</SMTPFrom>
<From>noreply</From>
<FromEmail>noreply@domain.com</FromEmail>
<ReplyTo>reply@domain.com</ReplyTo>
<MessagePlain>Hello,\r\nThis is a test message.\r\nThank you.</MessagePlain>
<MessageHTML><![CDATA[<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>]]></MessageHTML>
<Destinations>
<Destination>
<Recipient>john.doe@example.com</Recipient>
<Attention>John Doe</Attention>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Company>Example Corp</Company>
<Custom1></Custom1>
<Custom2></Custom2>
</Destination>
<Destination><Recipient>recipient.two@example.com</Recipient></Destination>
<Destination><Recipient>recipient.three@example.com</Recipient></Destination>
<Destination><Recipient>recipient.four@example.com</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
<File>
<Name>Sample2.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</EmailRequest>'
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
class SimpleXMLExtended extends SimpleXMLElement {
//
// this class extends SimplXMLElement to insert CDATA if necessary.
// for example, XML is not validated if HTML tag is inside XML Element,
// so we want to wrap inside CDATA, <![CDATA[<html>...</html>]]>
//
public function addCData($cdata_text) {
$node = dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
$authToken = "[Your Auth Token]";
$data = new SimpleXMLExtended("<?xml version=\"1.0\" encoding=\"utf-8\"?><EmailRequest></EmailRequest>");
$data->addChild("MessageData");
$data->MessageData->addChild("EmailSubject","Test Email Subject");
$data->MessageData->addChild("MessagePlain","Hello, This is a test message. Thank you.");
$destinations = $data->MessageData->addChild("Destinations");
$destination1 = $destinations->addChild("Destination");
$destination1->addChild("Recipient","recipient.one@example.com");
$destination2 = $destinations->addChild("Destination");
$destination2->addChild("Recipient","recipient.two@example.com");
$headers = array(
"Content-Type: application/xml",
"Accept: application/xml",
"encoding='utf-8'",
"Content-length: ".strlen($data->asXML()),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/email");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "400": // error
case "401": // unauthorized
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "500": // critical error
echo $response."\n";
echo $err;
break;
default:
echo $response."\n";
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
class SimpleXMLExtended extends SimpleXMLElement {
//
// this class extends SimplXMLElement to insert CDATA if necessary.
// for example, XML is not validated if HTML tag is inside XML Element,
// so we want to wrap inside CDATA, <![CDATA[<html>...</html>]]>
//
public function addCData($cdata_text) {
$node = dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
function GetBase64Contents($file_name)
{
// returns base64 encoded file data
if( file_exists($file_name) )
{
$fp = fopen($file_name,"r");
$file_content = fread($fp,filesize($file_name));
fclose($fp);
return base64_encode($file_content);
}
}
$authToken = "[Your Auth Token]";
$message_id = "ID123456"; //optional
$file1 = "D:\\file1.pdf";
$file2 = "D:\\file2.pdf";
$data = new SimpleXMLExtended("<?xml version=\"1.0\" encoding=\"utf-8\"?><EmailRequest></EmailRequest>");
$data->addChild("MessageData");
$data->MessageData->addChild("MessageID",$message_id);
$data->MessageData->addChild("Reference","Test1");
$data->MessageData->addChild("WebhookCallbackURL","https://www.example.com/webhook");
$data->MessageData->addChild("WebhookCallbackFormat","XML");
$data->MessageData->addChild("SendTime","2022-08-01T09:00:00");
$data->MessageData->addChild("TimeZone","New Zealand");
$data->MessageData->addChild("SubAccount","SubAccount01");
$data->MessageData->addChild("Department","Department01");
$data->MessageData->addChild("ChargeCode","BillingGroup01");
$data->MessageData->addChild("EmailSubject","Test Email Subject");
$data->MessageData->addChild("SMTPFrom","noreply@example.com");
$data->MessageData->addChild("From","noreply");
$data->MessageData->addChild("FromEmail","noreply@example.com");
$data->MessageData->addChild("ReplyTo","reply@example.com");
$data->MessageData->addChild("MessagePlain","Hello,\r\nThis is a test message.\r\nThank you.");
$data->MessageData->addChild("MessageHTML");
$data->MessageData->MessageHTML->addCData("<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>"); // wrap CDATA for HTML Tags
$destinations = $data->MessageData->addChild("Destinations");
$destination1 = $destinations->addChild("Destination");
$destination1->addChild("Recipient","john.doe@example.com");
$destination1->addChild("Attention","John Doe");
$destination1->addChild("FirstName","John");
$destination1->addChild("LastName","Doe");
$destination1->addChild("Company","Example Corp");
$destination1->addChild("Custom1","");
$destination1->addChild("Custom2","");
$destination2 = $destinations->addChild("Destination");
$destination2->addChild("Recipient","recipient.two@example.com");
$destination3 = $destinations->addChild("Destination");
$destination3->addChild("Recipient","recipient.three@example.com");
$destination4 = $destinations->addChild("Destination");
$destination4->addChild("Recipient","recipient.four@example.com");
if( file_exists($file1) || file_exists($file2) )
{
$fileElement = $data->MessageData->addChild("Files");
if( file_exists($file1) )
{
$fileElement1 = $fileElement->addChild("File");
$fileElement1->addChild("Name",basename($file1));
$fileElement1->addChild("Data",GetBase64Contents($file1));
}
if( file_exists($file2) )
{
$fileElement2 = $fileElement->addChild("File");
$fileElement2->addChild("Name",basename($file2));
$fileElement2->addChild("Data",GetBase64Contents($file2));
}
}
$headers = array(
"Content-Type: application/xml",
"Accept: application/xml",
"encoding='utf-8'",
"Content-length: ".strlen($data->asXML()),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/email");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "400": // error
case "401": // unauthorized
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "500": // critical error
echo $response."\n";
echo $err;
break;
default:
echo $response."\n";
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;
namespace TNZ
{
class Program
{
private static XmlNode addChildNode(XmlDocument xmlDoc, string name, string val)
{
XmlNode workingNode = xmlDoc.CreateElement(name);
workingNode.InnerText = val;
return workingNode;
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/email";
string authToken = "[Your Auth Token]";
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); // <?xml version="1.0" encoding="UTF-8"?>
xmlDoc.AppendChild(docNode);
XmlNode rootNode = xmlDoc.CreateElement("EmailRequest");
xmlDoc.AppendChild(rootNode);
//
// MessageData
//
XmlNode messageDataNode = xmlDoc.CreateElement("MessageData");
messageDataNode.AppendChild(addChildNode(xmlDoc, "EmailSubject", "Test Email Subject"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "MessagePlain", "Hello,\r\nThis is a test message.\r\nThank you."));
//
// Add Destinations
//
XmlNode workingNode = xmlDoc.CreateElement("Destinations");
// Declare Single Destination
XmlNode destNode1 = xmlDoc.CreateElement("Destination");
destNode1.AppendChild(addChildNode(xmlDoc, "Recipient", "recipient.one@example.com"));
// Add Destination to Destinations object
workingNode.AppendChild(destNode1);
// Declare Single Destination
XmlNode destNode2 = xmlDoc.CreateElement("Destination");
destNode2.AppendChild(addChildNode(xmlDoc, "Recipient", "recipient.two@example.com"));
// Add Destination to Destinations object
workingNode.AppendChild(destNode2);
// Add Destinations to MessageData
messageDataNode.AppendChild(workingNode);
//
// Set MessageData into root(EmailRequest) node
//
rootNode.AppendChild(messageDataNode);
//
// Send HTTP Request to REST API
//
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/xml; encoding='utf-8'";
request.Accept = "application/xml; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream(); //open connection
stream.Write(byteArray, 0, byteArray.Length); // Send the data.
stream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;
namespace TNZ
{
class Program
{
private static string GetFileName(string strFileLocation)
{
return System.IO.Path.GetFileName(strFileLocation);
}
private static string GetFileContents(string strFileLocation)
{
//
// Read files in bytes, convert to Base64String and return in string
//
using (FileStream reader = new FileStream(strFileLocation, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
string strContent = Convert.ToBase64String(buffer);
ASCIIEncoding encoding = new ASCIIEncoding();
return Encoding.ASCII.GetString(encoding.GetBytes(strContent));
}
}
private static XmlNode addChildNode(XmlDocument xmlDoc, string name, string val)
{
XmlNode workingNode = xmlDoc.CreateElement(name);
workingNode.InnerText = val;
return workingNode;
}
private static XmlNode addChildNodeCDATA(XmlDocument xmlDoc, string name, string val)
{
XmlNode workingNode = xmlDoc.CreateElement(name);
workingNode.InnerXml = @"<![CDATA[" + val + "]]>";
return workingNode;
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/email";
string authToken = "[Your Auth Token]";
string file1 = "[File Location]/Sample1.pdf";
string file2 = "[File Location]/Sample2.pdf";
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); // <?xml version="1.0" encoding="UTF-8"?>
xmlDoc.AppendChild(docNode);
XmlNode rootNode = xmlDoc.CreateElement("EmailRequest");
xmlDoc.AppendChild(rootNode);
//
// MessageData
//
XmlNode messageDataNode = xmlDoc.CreateElement("MessageData");
messageDataNode.AppendChild(addChildNode(xmlDoc, "MessageID", "ID123456"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "Reference", "Test1"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "WebhookCallbackURL", "https://www.example.com/webhook"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "WebhookCallbackFormat", "XML"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "SendTime", "2022-08-01T09:00:00"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "TimeZone", "New Zealand"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "SubAccount", "SubAccount01"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "Department", "Department01"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "ChargeCode", "BillingGroup01"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "EmailSubject", "Test Email Subject"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "SMTPFrom", "noreply@example.com"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "From", "noreply"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "FromEmail", "noreply@example.com"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "ReplyTo", "reply@example.com"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "MessagePlain", "Hello,\r\nThis is a test message.\r\nThank you."));
messageDataNode.AppendChild(addChildNodeCDATA(xmlDoc, "MessageHTML", "<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>")); // wrap with <![CDATA[]]>
//
// Add Destinations 1 - Add with details
//
XmlNode workingNode = xmlDoc.CreateElement("Destinations");
XmlNode destNode = xmlDoc.CreateElement("Destination");
destNode.AppendChild(addChildNode(xmlDoc, "Recipient", "john.doe@example.com"));
destNode.AppendChild(addChildNode(xmlDoc, "Attention", "John Doe"));
destNode.AppendChild(addChildNode(xmlDoc, "FirstName", "John"));
destNode.AppendChild(addChildNode(xmlDoc, "LastName", "Doe"));
destNode.AppendChild(addChildNode(xmlDoc, "Company", "Example Corp"));
destNode.AppendChild(addChildNode(xmlDoc, "Custom1", "Custom1"));
destNode.AppendChild(addChildNode(xmlDoc, "Custom2", "Custom2"));
workingNode.AppendChild(destNode);
//
// Add Destinations 2 - Add emails only
//
destNode = xmlDoc.CreateElement("Destination");
destNode.AppendChild(addChildNode(xmlDoc, "Recipient", "recipient.two@example.com"));
workingNode.AppendChild(destNode);
destNode = xmlDoc.CreateElement("Destination");
destNode.AppendChild(addChildNode(xmlDoc, "Recipient", "recipient.three@example.com"));
workingNode.AppendChild(destNode);
// Add Destinations to MessageData
messageDataNode.AppendChild(workingNode);
//
// Attach File 1
//
workingNode = xmlDoc.CreateElement("Files");
XmlNode fileNode1 = xmlDoc.CreateElement("File");
fileNode1.AppendChild(addChildNode(xmlDoc, "Name", GetFileName(file1)));
fileNode1.AppendChild(addChildNodeCDATA(xmlDoc, "Data", GetFileContents(file1)));
workingNode.AppendChild(fileNode1);
//
// Attach File 2
//
XmlNode fileNode2 = xmlDoc.CreateElement("File");
fileNode2.AppendChild(addChildNode(xmlDoc, "Name", GetFileName(file1)));
fileNode2.AppendChild(addChildNodeCDATA(xmlDoc, "Data", GetFileContents(file1)));
workingNode.AppendChild(fileNode2);
messageDataNode.AppendChild(workingNode);
//
// Set MessageData into root node
//
rootNode.AppendChild(messageDataNode);
//
// Send HTTP Request to REST API
//
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/xml; encoding='utf-8'";
request.Accept = "application/xml; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream(); //open connection
stream.Write(byteArray, 0, byteArray.Length); // Send the data.
stream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import xml.etree.ElementTree as ET
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/email"
headers = {
"Content-Type": "application/xml",
"Accept": "application/xml",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
root = ET.Element('EmailRequest')
message_data = ET.SubElement(root,"MessageData")
ET.SubElement(message_data, "EmailSubject").text = "Test Email Subject"
ET.SubElement(message_data, "MessagePlain").text = "Hello, This is a test message. Thank you."
destinations = ET.SubElement(message_data,"Destinations")
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "recipient.one@example.com"
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "recipient.two@example.com"
r = requests.post(url, data=ET.tostring(root,'utf-8'), headers=headers)
print(r)
print(r.text)
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/email
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import base64
import xml.etree.ElementTree as ET
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/email"
headers = {
"Content-Type": "application/xml",
"Accept": "application/xml",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
file_data_1 = base64.b64encode(open("[File Location]/Sample1.pdf","rb").read()).decode("utf-8")
file_data_2 = base64.b64encode(open("[File Location]/Sample2.pdf","rb").read()).decode("utf-8")
root = ET.Element('EmailRequest')
message_data = ET.SubElement(root,"MessageData")
ET.SubElement(message_data, "MessageID").text = "ID123456"
ET.SubElement(message_data, "Reference").text = "Test1"
ET.SubElement(message_data, "WebhookCallbackURL").text = "https://www.example.com/webhook"
ET.SubElement(message_data, "WebhookCallbackFormat").text = "XML"
ET.SubElement(message_data, "SendTime").text = "2022-08-01T09:00:00"
ET.SubElement(message_data, "TimeZone").text = "New Zealand"
ET.SubElement(message_data, "SubAccount").text = "SubAccount01"
ET.SubElement(message_data, "Department").text = "Department01"
ET.SubElement(message_data, "ChargeCode").text = "BillingGroup01"
ET.SubElement(message_data, "EmailSubject").text = "Test Email Subject"
ET.SubElement(message_data, "SMTPFrom").text = "noreply@example.com"
ET.SubElement(message_data, "From").text = "noreply"
ET.SubElement(message_data, "FromEmail").text = "noreply@example.com"
ET.SubElement(message_data, "ReplyTo").text = "reply@example.com"
ET.SubElement(message_data, "MessagePlain").text = "Hello,\r\nThis is a test message.\r\nThank you."
ET.SubElement(message_data, "MessageHTML").text = "<![CDATA[<html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html>]]>"
destinations = ET.SubElement(message_data,"Destinations")
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination,"Recipient").text = "john.doe@example.com"
ET.SubElement(destination,"Attention").text = "John Doe"
ET.SubElement(destination,"FirstName").text = "John"
ET.SubElement(destination,"LastName").text = "Doe"
ET.SubElement(destination,"Company").text = "Example Corp"
ET.SubElement(destination,"Custom1").text = ""
ET.SubElement(destination,"Custom2").text = ""
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "recipient.two@example.com"
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "recipient.three@example.com"
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "recipient.four@example.com"
files = ET.SubElement(message_data,"Files")
file = ET.SubElement(files,"File")
ET.SubElement(file,"Name").text = "Sample1.pdf"
ET.SubElement(file,"Data").text = file_data_1
file = ET.SubElement(files,"File")
ET.SubElement(file,"Name").text = "Sample2.pdf"
ET.SubElement(file,"Data").text = file_data_2
r = requests.post(url, data=ET.tostring(root,'utf-8'), headers=headers)
print(r)
print(r.text)
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
Parameter | Example Value | Description | |
---|---|---|---|
Content-Type | application/xml; encoding='utf-8' application/json; encoding='utf-8' |
Sets the request data format of request | |
Accept | application/xml; encoding='utf-8' application/json; encoding='utf-8' |
Sets the return data format of request | |
Authorization | Basic eyJhbGciOiJI...adQssw5c | Auth Token value set up in Create a new API Auth token |
Parameter | Example Value | Description | |
---|---|---|---|
EmailSubject | Test Email Subject | Subject field used in the email | |
SMTPFrom | noreply@example.com | Sets the email Sender/Return-Path at the SMTP level (this address receives bounce-back emails and is used for SPF/DKIM type authentication; 'FromEmail' is used if not specified) | |
From | noreply | Sets the email sender's Friendly Name (seen by the email recipient) | |
FromEmail | noreply@example.com | Sets the email sender's Email Address (seen by the email recipient; API 'Sender' is used if not specified) | |
ReplyTo | reply@example.com | Sets the email sender's Reply-To Address (if the recipient replies, the Reply To will receive the reply) | |
MessagePlain | Hello, This is a test message. Thank you. |
Content used for the message/plain section of the email (overrides 'Template') | |
Destinations | > Recipient | john.doe@example.com recipient.three@example.com recipient.four@example.com |
Email address(es) to receive the message (for detailed formatting, see the Destinations parameter below) |
Parameter | Example Value | Description | |
---|---|---|---|
MessageID | ID123456 | A message tracking identifier (maximum 40 characters, alphanumeric). If you do not supply this field, the API will return one for you in the response body (UUID v4 of 36 characters) | |
Reference | Test1 | Tracking ID or message description | |
WebhookCallbackURL | https://www.example.com/webhook | Overrides your Sender's default Webhook URL. Requires a default webhook to be configured. A full path including https:// is required. | |
WebhookCallbackFormat | JSON | Overrides your Sender's default Webhook format ('JSON' or 'XML') | |
SendTime | 2022-12-31T23:00 | Delay sending until the specified date/time, a single point of time in a combined date and time representation ({date}T{time}; for example, 2022-08-29T04:00 in your local timezone, specified by your Sender setting or overridden using the TimeZone command). | |
TimeZone | New Zealand | User's local timezone (see Setting Timezones) | |
SubAccount | SubAccount01 | Used for reporting, billing and Web Dashboard segmentation. See the TNZ API Structure guide's Cost Tracking & Rebilling section. | |
Department | Department01 | Used for reporting, billing and Web Dashboard segmentation. See the TNZ API Structure guide's Cost Tracking & Rebilling section. | |
ChargeCode | BillingGroup01 | Bespoke app cost allocation code (for invoice segmentation) | |
TemplateLocation | Folder 01 | Directory/location of Template to use | |
Template | Template File Name | Preloaded Template to use for email body (overridden by MessagePlain and/or MessageHTML parameters) | |
MessageHTML | <html>Hello,<br /><br />This is a test message.<br /><br />Thank you.</html> | Content used for the message/html section of the email (overrides 'Template' and 'MessagePlain') | |
Destinations | > Recipient | john.doe@example.com | Recipient of the email |
> Attention | John Doe | Recipient's name | |
> First Name | John | Recipient's first name | |
> Last Name | Doe | Recipient's last name | |
> Company | Example Corp | Recipient's company | |
> Custom1 | Reference Number ABC123 | Customisable tracking and personalisation field | |
> Custom2 | Reference Code WWW222 | Customisable tracking and personalisation field | |
Files | > Name | Sample.pdf | Attachment's filename |
> Data | %%Base-64%% | Base-64 encoded value of the attached file |
HTTP Method: POST
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
{
"MessageData" :
{
"Message": "Hello, this is a test message from Department01. Thank you.",
"Destinations" :
[
{ "Recipient": "+6421000001" },
{ "Recipient": "+6421000002" }
]
}
}
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
{
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"FromNumber": "6422000001",
"SMSEmailReply": "person.one@domain.com",
"CharacterConversion": true,
"Message": "Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]",
"Destinations" :
[
{
"Recipient": "+6421000001",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "+6421000002" },
{ "Recipient": "+6421000003" },
{ "Recipient": "+6421000004" }
],
"Files":
[
{
"Name": "Sample.pdf",
"Data": "%%BASE-64 CONTENT%%"
},
{
"Name": "Sample2.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/sms \
--header "Content-Type: application/json; encoding='utf-8'" \
--header "Accept: application/json; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '{
"MessageData" :
{
"Message": "Hello, this is a test message from Department01. Thank you.",
"Destinations" :
[
{ "Recipient": "+6421000001" },
{ "Recipient": "+6421000002" }
]
}
}'
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/sms \
--header "Content-Type: application/json; encoding='utf-8'" \
--header "Accept: application/json; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '{
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"FromNumber": "6422000001",
"SMSEmailReply": "person.one@domain.com",
"CharacterConversion": true,
"Message": "Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]",
"Destinations" :
[
{
"Recipient": "+6421000001",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "+6421000002" },
{ "Recipient": "+6421000003" },
{ "Recipient": "+6421000004" }
],
"Files":
[
{
"Name": "Sample.pdf",
"Data": "%%BASE-64 CONTENT%%"
},
{
"Name": "Sample2.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}'
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
$authToken = "[Your Auth Token]";
$data = array(
"MessageData" => array(
"Message" => "Hello, this is a test message from Department01. Thank you.",
"Destinations" => array(
array(
"Recipient" => "+6421000001"
),
array(
"Recipient" => "+6421000002"
),
),
)
);
$headers = array(
"Content-Type: application/json",
"Accept: application/json",
"encoding='utf-8'",
"Content-length: ".strlen(json_encode($data)),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header('Content-Type: application/json');
echo $response;
break;
case "400": // error
case "401": // unauthorized
header('Content-Type: application/json');
echo $response;
break;
case "500": // critical error
echo $response;
echo $err;
break;
default:
echo $response;
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
function GetBase64Contents($file_name)
{
// returns base64 encoded file data
if( file_exists($file_name) )
{
$fp = fopen($file_name,"r");
$file_content = fread($fp,filesize($file_name));
fclose($fp);
return base64_encode($file_content);
}
}
$authToken = "[Your Auth Token]";
$message_id = "ID123456"; // optional
$file1 = "Sample.pdf";
$file2 = "Sample2.pdf";
$data = array(
"MessageData" => array(
"MessageID" => $message_id,
"Reference" => "Test1",
"WebhookCallbackURL" => "https://www.example.com/webhook",
"WebhookCallbackFormat" => "JSON",
"SendTime" => "2022-08-01T09:00:00",
"TimeZone" => "New Zealand",
"SubAccount" => "SubAccount01",
"Department" => "Department01",
"ChargeCode" => "BillingGroup01",
"FromNumber" => "6422000001",
"SMSEmailReply" => "person.one@domain.com",
"CharacterConversion" => true,
"Message" => "Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]",
"Destinations" => array(
array(
"Recipient" => "+6421000001",
"Attention" => "John Doe",
"First Name" => "John",
"Last Name" => "Doe",
"Company" => "Example Corp",
"Custom1" => "",
"Custom2" => ""
),
array( "Recipient" => "+6421000002" ),
array( "Recipient" => "+6421000003" ),
array( "Recipient" => "+6421000004" )
),
"Files" => array(
array(
"Name" => basename($file1),
"Data" => GetBase64Contents($file1)
),
array(
"Name" => basename($file2),
"Data" => GetBase64Contents($file2)
)
),
)
);
$headers = array(
"Content-Type: application/json",
"Accept: application/json",
"encoding='utf-8'",
"Content-length: ".strlen(json_encode($data)),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header('Content-Type: application/json');
echo $response;
break;
case "400": // error
case "401": // unauthorized
header('Content-Type: application/json');
echo $response;
break;
case "500": // critical error
echo $response;
echo $err;
break;
default:
echo $response;
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
namespace TNZ
{
class Program
{
private static string addslashes(string str)
{
string ret = "";
foreach (char c in str)
{
switch (c)
{
case '\'': ret += "\\\'"; break;
case '\"': ret += "\\\""; break;
case '\0': ret += "\\0"; break;
case '\r': ret += "\\r"; break;
case '\n': ret += "\\n"; break;
case '\\': ret += "\\\\"; break;
default: ret += c.ToString(); break;
}
}
return ret;
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/sms";
string authToken = "[Your Auth Token]";
string strJSONData = $@"{{
""MessageData"": {{
""Message"": ""{addslashes("Hello, This is a test message. Thank you.")}"",
""Destinations"":
[
{{ ""Recipient"": ""+6421000001"" }},
{{ ""Recipient"": ""+6421000002"" }}
]
}}
}}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json; encoding='utf-8'";
request.Accept = "application/json; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(strJSONData);
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
namespace TNZ
{
class Program
{
private static string GetFileContents(string strFileLocation)
{
//
// Read files in bytes, convert to Base64String and return in string
//
using (FileStream reader = new FileStream(strFileLocation, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
string strContent = Convert.ToBase64String(buffer);
ASCIIEncoding encoding = new ASCIIEncoding();
return Encoding.ASCII.GetString(encoding.GetBytes(strContent));
}
}
private static string addslashes(string str)
{
string ret = "";
foreach (char c in str)
{
switch (c)
{
case '\'': ret += "\\\'"; break;
case '\"': ret += "\\\""; break;
case '\0': ret += "\\0"; break;
case '\r': ret += "\\r"; break;
case '\n': ret += "\\n"; break;
case '\\': ret += "\\\\"; break;
default: ret += c.ToString(); break;
}
}
return ret;
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/sms";
string authToken = "[Your Auth Token]";
string sender = "application@domain.com";
string api_key = "ta8wr7ymd";
string file1 = "D:\\File1.pdf";
string file2 = "D:\\File2.pdf";
string file1_data = GetFileContents(file1);
string file2_data = GetFileContents(file2);
StringBuilder sb = new StringBuilder();
string strJSONData = $@"{{
""MessageData"": {{
""MessageID"": ""ID123456"",
""Reference"": ""Test1"",
""WebhookCallbackURL"":""https://www.example.com/webhook"",
""WebhookCallbackFormat"":""JSON"",
""SendTime"": ""2022-08-01T09:00:00"",
""TimeZone"": ""New Zealand"",
""SubAccount"": ""SubAccount01"",
""Department"": ""Department01"",
""ChargeCode"": """",
""FromNumber"": ""+61422000001"",
""SMSEmailReply"": ""reply@example.com"",
""CharacterConversion"": true,
""Message"": ""{addslashes("Hello,\r\nThis is a test message.\r\nThank you.\r\nClick [[File1]], [[File2]]")}"",
""Destinations"":
[
{{
""Recipient"": ""+6421000001"",
""Attention"": ""John Doe"",
""First Name"": ""John"",
""Last Name"": ""Doe"",
""Company"": ""Example Corp""
}},
{{ ""Recipient"": ""+6422000001"", ""Attention"": ""Recipient 2"" }},
{{ ""Recipient"": ""+6423000001"" }},
{{ ""Recipient"": ""+6424000001"" }}
],
""Files"":
[
{{
""Name"": ""File1.pdf"",
""Data"": ""{file1_data}""
}},
{{
""Name"": ""File2.pdf"",
""Data"": ""{file2_data}""
}}
]
}}
}}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json; encoding='utf-8'";
request.Accept = "application/json; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(strJSONData);
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import json
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/sms"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
data = {
"MessageData" :
{
"Message": "Hello, this is a test message from Department01. Thank you.",
"Destinations" :
[
{ "Recipient": "+6421000001" },
{ "Recipient": "+6421000002" },
]
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
print(r.text)
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import json
import base64
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/sms"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
file_list = [
{
"name": "File1.pdf",
"path": "d:/File1.pdf"
},
{
"name": "File2.pdf",
"path": "d:/File2.pdf"
}
]
data = {
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"FromNumber": "6422000001",
"SMSEmailReply": "person.one@domain.com",
"CharacterConversion": True,
"Message": "Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]",
"Destinations" :
[
{
"Recipient": "+6421000001",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "+6421000002" },
{ "Recipient": "+6421000003" },
{ "Recipient": "+6421000004" }
],
"Files" :
[
{
"Name": file_list[0]["name"],
"Data": base64.b64encode(open(file_list[0]["path"],"rb").read()).decode("utf-8")
},
{
"Name": file_list[1]["name"],
"Data": base64.b64encode(open(file_list[1]["path"],"rb").read()).decode("utf-8")
},
]
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
print(r.text)
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?xml version="1.0" encoding="UTF-8"?>
<SMSRequest>
<MessageData>
<Message>Hello, this is a test message from Department01. Thank you.</Message>
<Destinations>
<Destination><Recipient>+6421000001</Recipient></Destination>
<Destination><Recipient>+6421000002</Recipient></Destination>
</Destinations>
</MessageData>
</SMSRequest>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?xml version="1.0" encoding="UTF-8"?>
<SMSRequest>
<MessageData>
<MessageID>ID123456</MessageID>
<Reference>Test1</Reference>
<WebhookCallbackURL>https://www.example.com/webhook</WebhookCallbackURL>
<WebhookCallbackFormat>XML</WebhookCallbackFormat>
<SendTime>2022-08-01T09:00:00</SendTime>
<TimeZone>New Zealand</TimeZone>
<SubAccount>SubAccount01</SubAccount>
<Department>Department01</Department>
<ChargeCode>BillingGroup01</ChargeCode>
<FromNumber>6422000001</FromNumber>
<SMSEmailReply>person.one@domain.com</SMSEmailReply>
<CharacterConversion>true</CharacterConversion>
<Message>Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]</Message>
<Destinations>
<Destination>
<Recipient>+6421000001</Recipient>
<Attention>John Doe</Attention>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Company>Example Corp</Company>
<Custom1></Custom1>
<Custom2></Custom2>
</Destination>
<Destination><Recipient>+6421000002</Recipient></Destination>
<Destination><Recipient>+6421000003</Recipient></Destination>
<Destination><Recipient>+6421000004</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
<File>
<Name>Sample2.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</SMSRequest>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/sms \
--header "Content-Type: application/xml; encoding='utf-8'" \
--header "Accept: application/xml; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '<?xml version="1.0" encoding="UTF-8"?>
<SMSRequest>
<Sender>application@domain.com</Sender>
<APIKey>ta8wr7ymd</APIKey>
<MessageData>
<Message>Hello, this is a test message from Department01. Thank you.</Message>
<Destinations>
<Destination><Recipient>+6421000001</Recipient></Destination>
<Destination><Recipient>+6421000002</Recipient></Destination>
</Destinations>
</MessageData>
</SMSRequest>'
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/sms \
--header "Content-Type: application/xml; encoding='utf-8'" \
--header "Accept: application/xml; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '<?xml version="1.0" encoding="UTF-8"?>
<SMSRequest>
<MessageData>
<MessageID>ID123456</MessageID>
<Reference>Test1</Reference>
<WebhookCallbackURL>https://www.example.com/webhook</WebhookCallbackURL>
<WebhookCallbackFormat>XML</WebhookCallbackFormat>
<SendTime>2022-08-01T09:00:00</SendTime>
<TimeZone>New Zealand</TimeZone>
<SubAccount>SubAccount01</SubAccount>
<Department>Department01</Department>
<ChargeCode>BillingGroup01</ChargeCode>
<FromNumber>6422000001</FromNumber>
<SMSEmailReply>person.one@domain.com</SMSEmailReply>
<CharacterConversion>true</CharacterConversion>
<Message>Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]</Message>
<Destinations>
<Destination>
<Recipient>+6421000001</Recipient>
<Attention>John Doe</Attention>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Company>Example Corp</Company>
<Custom1></Custom1>
<Custom2></Custom2>
</Destination>
<Destination><Recipient>+6421000002</Recipient></Destination>
<Destination><Recipient>+6421000003</Recipient></Destination>
<Destination><Recipient>+6421000004</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
<File>
<Name>Sample2.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</SMSRequest>'
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
$authToken = "[Your Auth Token]";
$data = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><SMSRequest></SMSRequest>");
$data->addChild("MessageData");
$data->MessageData->addChild("Message","Hello, this is a test message from Department01. Thank you.");
$destinations = $data->MessageData->addChild("Destinations");
$destination1 = $destinations->addChild("Destination");
$destination1->addChild("Recipient","+6421000001");
$destination2 = $destinations->addChild("Destination");
$destination2->addChild("Recipient","+6421000002");
$headers = array(
"Content-Type: application/xml",
"Accept: application/xml",
"encoding='utf-8'",
"Content-length: ".strlen($data->asXML()),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "400": // error
case "401": // unauthorized
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "500": // critical error
echo $response."\n";
echo $err;
break;
default:
echo $response."\n";
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
function GetBase64Contents($file_name)
{
// returns base64 encoded file data
if( file_exists($file_name) )
{
$fp = fopen($file_name,"r");
$file_content = fread($fp,filesize($file_name));
fclose($fp);
return base64_encode($file_content);
}
}
$authToken = "[Your Auth Token]";
$file1 = "Sample.pdf";
$file2 = "Sample2.pdf";
$data = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><SMSRequest></SMSRequest>");
$data->addChild("MessageData");
$data->MessageData->addChild("MessageID","ID123456");
$data->MessageData->addChild("Reference","Test1");
$data->MessageData->addChild("WebhookCallbackURL","https://www.example.com/webhook");
$data->MessageData->addChild("WebhookCallbackFormat","XML");
$data->MessageData->addChild("SendTime","2022-08-01T09:00:00");
$data->MessageData->addChild("TimeZone","New Zealand");
$data->MessageData->addChild("SubAccount","SubAccount01");
$data->MessageData->addChild("Department","Department01");
$data->MessageData->addChild("ChargeCode","BillingGroup01");
$data->MessageData->addChild("FromNumber","6422000001");
$data->MessageData->addChild("SMSEmailReply","person.one@domain.com");
$data->MessageData->addChild("CharacterConversion",true);
$data->MessageData->addChild("Message","Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]");
$destinations = $data->MessageData->addChild("Destinations");
$destination1 = $destinations->addChild("Destination");
$destination1->addChild("Recipient","+6421000001");
$destination1->addChild("Attention","John Doe");
$destination1->addChild("FirstName","John");
$destination1->addChild("LastName","Doe");
$destination1->addChild("Company","Example Corp");
$destination1->addChild("Custom1","");
$destination1->addChild("Custom2","");
$destination2 = $destinations->addChild("Destination");
$destination2->addChild("Recipient","+6421000002");
$destination3 = $destinations->addChild("Destination");
$destination3->addChild("Recipient","+6421000003");
$destination4 = $destinations->addChild("Destination");
$destination4->addChild("Recipient","+6421000004");
if( file_exists($file_name1) || file_exists($file_name2) )
{
$fileElement = $data->MessageData->addChild("Files");
if( file_exists($file_name1) )
{
$fileElement1 = $fileElement->addChild("File");
$fileElement1->addChild("Name",basename($file1));
$fileElement1->addChild("Data",GetBase64Contents($file_content1));
}
if( file_exists($file_name2) )
{
$fileElement2 = $fileElement->addChild("File");
$fileElement2->addChild("Name",basename($file1));
$fileElement2->addChild("Data",GetBase64Contents($file_content2));
}
}
$headers = array(
"Content-Type: application/xml",
"Accept: application/xml",
"encoding='utf-8'",
"Content-length: ".strlen($data->asXML()),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "400": // error
case "401": // unauthorized
header("Content-Type: application/xml; encoding='utf-8'");
echo $response;
break;
case "500": // critical error
echo $response."\n";
echo $err;
break;
default:
echo $response."\n";
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;
namespace TNZ
{
class Program
{
private static string addslashes(string str)
{
string ret = "";
foreach (char c in str)
{
switch (c)
{
case '\'': ret += "\\\'"; break;
case '\"': ret += "\\\""; break;
case '\0': ret += "\\0"; break;
case '\r': ret += "\\r"; break;
case '\n': ret += "\\n"; break;
case '\\': ret += "\\\\"; break;
default: ret += c.ToString(); break;
}
}
return ret;
}
private static XmlNode addChildNode(XmlDocument xmlDoc, string name, string val)
{
XmlNode workingNode = xmlDoc.CreateElement(name);
workingNode.InnerText = val;
return workingNode;
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/sms";
string authToken = "[Your Auth Token]";
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); // <?xml version="1.0" encoding="UTF-8"?>
xmlDoc.AppendChild(docNode);
XmlNode rootNode = xmlDoc.CreateElement("SMSRequest");
xmlDoc.AppendChild(rootNode);
//
// MessageData
//
XmlNode messageDataNode = xmlDoc.CreateElement("MessageData");
messageDataNode.AppendChild(addChildNode(xmlDoc, "Message", addslashes("Hello,\r\nThis is a test message.\r\nThank you.")));
//
// Add Destinations
//
XmlNode workingNode = xmlDoc.CreateElement("Destinations");
// Declare Single Destination
XmlNode destNode1 = xmlDoc.CreateElement("Destination");
destNode1.AppendChild(addChildNode(xmlDoc, "Recipient", "+6421000001"));
// Add Destination to Destinations object
workingNode.AppendChild(destNode1);
// Declare Single Destination
XmlNode destNode2 = xmlDoc.CreateElement("Destination");
destNode2.AppendChild(addChildNode(xmlDoc, "Recipient", "+6421000002"));
// Add Destination to Destinations object
workingNode.AppendChild(destNode2);
// Add Destinations to MessageData
messageDataNode.AppendChild(workingNode);
//
// Set MessageData into root(EmailRequest) node
//
rootNode.AppendChild(messageDataNode);
//
// Send HTTP Request to REST API
//
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/xml; encoding='utf-8'";
request.Accept = "application/xml; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream(); //open connection
stream.Write(byteArray, 0, byteArray.Length); // Send the data.
stream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;
namespace TNZ
{
class Program
{
private static string addslashes(string str)
{
string ret = "";
foreach (char c in str)
{
switch (c)
{
case '\'': ret += "\\\'"; break;
case '\"': ret += "\\\""; break;
case '\0': ret += "\\0"; break;
case '\r': ret += "\\r"; break;
case '\n': ret += "\\n"; break;
case '\\': ret += "\\\\"; break;
default: ret += c.ToString(); break;
}
}
return ret;
}
private static string GetFileName(string strFileLocation)
{
return System.IO.Path.GetFileName(strFileLocation);
}
private static string GetFileContents(string strFileLocation)
{
//
// Read files in bytes, convert to Base64String and return in string
//
using (FileStream reader = new FileStream(strFileLocation, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
string strContent = Convert.ToBase64String(buffer);
ASCIIEncoding encoding = new ASCIIEncoding();
return Encoding.ASCII.GetString(encoding.GetBytes(strContent)).Trim();
}
}
private static XmlNode addChildNode(XmlDocument xmlDoc, string name, string val)
{
XmlNode workingNode = xmlDoc.CreateElement(name);
workingNode.InnerText = val;
return workingNode;
}
private static XmlNode addChildNodeCDATA(XmlDocument xmlDoc, string name, string val)
{
XmlNode workingNode = xmlDoc.CreateElement(name);
workingNode.InnerXml = @"<![CDATA[" + val + "]]>";
return workingNode;
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/sms";
string authToken = "[Your Auth Token]";
string file1 = "[File Location]/Sample1.pdf";
string file2 = "[File Location]/Sample2.pdf";
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); // <?xml version="1.0" encoding="UTF-8"?>
xmlDoc.AppendChild(docNode);
XmlNode rootNode = xmlDoc.CreateElement("SMSRequest");
xmlDoc.AppendChild(rootNode);
//
// MessageData
//
XmlNode messageDataNode = xmlDoc.CreateElement("MessageData");
messageDataNode.AppendChild(addChildNode(xmlDoc, "MessageID", "ID123456"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "Reference", "Test1"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "WebhookCallbackURL", "https://www.example.com/webhook"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "WebhookCallbackFormat", "XML"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "SendTime", "2022-08-01T09:00:00"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "TimeZone", "New Zealand"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "SubAccount", "SubAccount01"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "Department", "Department01"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "ChargeCode", "BillingGroup01"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "FromNumber", "+6422000001"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "SMSEmailReply", "person.one@domain.com"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "CharacterConversion", "true"));
messageDataNode.AppendChild(addChildNode(xmlDoc, "Message", addslashes("Hello,\r\nThis is a test message.\r\nThank you.")));
//
// Add Destinations 1 - Add with details
//
XmlNode workingNode = xmlDoc.CreateElement("Destinations");
XmlNode destNode = xmlDoc.CreateElement("Destination");
destNode.AppendChild(addChildNode(xmlDoc, "Recipient", "+6421000001"));
destNode.AppendChild(addChildNode(xmlDoc, "Attention", "John Doe"));
destNode.AppendChild(addChildNode(xmlDoc, "FirstName", "John"));
destNode.AppendChild(addChildNode(xmlDoc, "LastName", "Doe"));
destNode.AppendChild(addChildNode(xmlDoc, "Company", "Example Corp"));
destNode.AppendChild(addChildNode(xmlDoc, "Custom1", "Custom1"));
destNode.AppendChild(addChildNode(xmlDoc, "Custom2", "Custom2"));
workingNode.AppendChild(destNode);
//
// Add Destinations 2 - Add emails only
//
destNode = xmlDoc.CreateElement("Destination");
destNode.AppendChild(addChildNode(xmlDoc, "Recipient", "+6422000001"));
workingNode.AppendChild(destNode);
destNode = xmlDoc.CreateElement("Destination");
destNode.AppendChild(addChildNode(xmlDoc, "Recipient", "+6423000001"));
workingNode.AppendChild(destNode);
// Add Destinations to MessageData
messageDataNode.AppendChild(workingNode);
//
// Attach File 1
//
workingNode = xmlDoc.CreateElement("Files");
XmlNode fileNode1 = xmlDoc.CreateElement("File");
fileNode1.AppendChild(addChildNode(xmlDoc, "Name", GetFileName(file1)));
fileNode1.AppendChild(addChildNodeCDATA(xmlDoc, "Data", GetFileContents(file1)));
workingNode.AppendChild(fileNode1);
//
// Attach File 2
//
XmlNode fileNode2 = xmlDoc.CreateElement("File");
fileNode2.AppendChild(addChildNode(xmlDoc, "Name", GetFileName(file2)));
fileNode2.AppendChild(addChildNodeCDATA(xmlDoc, "Data", GetFileContents(file2)));
workingNode.AppendChild(fileNode2);
messageDataNode.AppendChild(workingNode);
//
// Set MessageData into root node
//
rootNode.AppendChild(messageDataNode);
//
// Send HTTP Request to REST API
//
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/xml; encoding='utf-8'";
request.Accept = "application/xml; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream(); //open connection
stream.Write(byteArray, 0, byteArray.Length); // Send the data.
stream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import xml.etree.ElementTree as ET
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/sms"
headers = {
"Content-Type": "application/xml",
"Accept": "application/xml",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
root = ET.Element('SMSRequest')
message_data = ET.SubElement(root,"MessageData")
ET.SubElement(message_data, "Message").text = "Hello, this is a call from test. This is relevant information."
destinations = ET.SubElement(message_data,"Destinations")
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "+6421000001"
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "+6421000002"
r = requests.post(url, data=ET.tostring(root,'utf-8'), headers=headers)
print(r)
print(r.text)
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/sms
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import base64
import xml.etree.ElementTree as ET
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/sms"
headers = {
"Content-Type": "application/xml",
"Accept": "application/xml",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
file_data_1 = base64.b64encode(open("d:/File1.pdf","rb").read()).decode("utf-8")
file_data_2 = base64.b64encode(open("d:/File2.pdf","rb").read()).decode("utf-8")
root = ET.Element('SMSRequest')
message_data = ET.SubElement(root,"MessageData")
ET.SubElement(message_data, "MessageID").text = "ID123456"
ET.SubElement(message_data, "Reference").text = "Test1"
ET.SubElement(message_data, "WebhookCallbackURL").text = "https://www.example.com/webhook"
ET.SubElement(message_data, "WebhookCallbackFormat").text = "XML"
ET.SubElement(message_data, "SendTime").text = "2022-08-01T09:00:00"
ET.SubElement(message_data, "TimeZone").text = "New Zealand"
ET.SubElement(message_data, "SubAccount").text = "SubAccount01"
ET.SubElement(message_data, "Department").text = "Department01"
ET.SubElement(message_data, "ChargeCode").text = "BillingGroup01"
ET.SubElement(message_data, "FromNumber").text = "6422000001"
ET.SubElement(message_data, "SMSEmailReply").text = "person.one@domain.com"
ET.SubElement(message_data, "CharacterConversion").text = "true"
ET.SubElement(message_data, "Message").text = "Hello, this is a test message. Click the link to download file1 [[File1]], and file2 [[File2]]"
destinations = ET.SubElement(message_data,"Destinations")
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination,"Recipient").text = "+6421000001"
ET.SubElement(destination,"Attention").text = "John Doe"
ET.SubElement(destination,"FirstName").text = "John"
ET.SubElement(destination,"LastName").text = "Doe"
ET.SubElement(destination,"Company").text = "Example Corp"
ET.SubElement(destination,"Custom1").text = ""
ET.SubElement(destination,"Custom2").text = ""
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "+6421000002"
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "+6421000003"
destination = ET.SubElement(destinations,"Destination")
ET.SubElement(destination, "Recipient").text = "+6421000004"
files = ET.SubElement(message_data,"Files")
file = ET.SubElement(files,"File")
ET.SubElement(file,"Name").text = "File1.pdf"
ET.SubElement(file,"Data").text = file_data_1
file = ET.SubElement(files,"File")
ET.SubElement(file,"Name").text = "File2.pdf"
ET.SubElement(file,"Data").text = file_data_2
r = requests.post(url, data=ET.tostring(root,'utf-8'), headers=headers)
print(r)
print(r.text)
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</ErrorMessage>
</root>
Parameter | Example Value | Description | |
---|---|---|---|
Content-Type | application/xml; encoding='utf-8' application/json; encoding='utf-8' |
Sets the request data format of request | |
Accept | application/xml; encoding='utf-8' application/json; encoding='utf-8' |
Sets the return data format of request | |
Authorization | Basic eyJhbGciOiJI...adQssw5c | Auth Token value set up in Create a new API Auth token |
Parameter | Example Value | Description | |
---|---|---|---|
Message | Hello, this is a test message from Department01. Thank you. | Plain or UTF-8 formatted SMS message | |
Destinations | > Recipient | +6421000002 +6421000003 +6421000004 |
Mobile number(s) to receive the message (for detailed formatting, see the Destinations parameter below) |
Parameter | Example Value | Description | |
---|---|---|---|
MessageID | ID123456 | A message tracking identifier (maximum 40 characters, alphanumeric). If you do not supply this field, the API will return one for you in the response body (UUID v4 of 36 characters) | |
Reference | Test1 | Tracking ID or message description | |
WebhookCallbackURL | https://www.example.com/webhook | Overrides your Sender's default Webhook URL. Requires a default webhook to be configured. A full path including https:// is required. | |
WebhookCallbackFormat | JSON | Overrides your Sender's default Webhook format ('JSON' or 'XML') | |
SendTime | 2021-12-31T23:00 | Delay sending until the specified date/time, a single point of time in a combined date and time representation ({date}T{time}; for example, 2017-08-29T04:00 in your local timezone, specified by your Sender setting or overridden using the TimeZone command). | |
TimeZone | New Zealand | User's local timezone (see Setting Timezones) | |
SubAccount | SubAccount01 | Used for reporting, billing and Web Dashboard segmentation. See the TNZ API Structure guide's Cost Tracking & Rebilling section. | |
Department | Department01 | Used for reporting, billing and Web Dashboard segmentation. See the TNZ API Structure guide's Cost Tracking & Rebilling section. | |
ChargeCode | BillingGroup01 | Bespoke app cost allocation code (for invoice segmentation) | |
FromNumber | 6421000001 | Setting SMS origination number, short code(s) will override in New Zealand - Not for New Zealand. | |
SMSEmailReply | person.one@domain.com | For email (SMTP) reply receipt notifications | |
CharacterConversion | true | Convert multi-byte characters into normalised GSM character format. ie. © to (C) | |
Message | Hello, view the link at [[Link:https://www.example.com/path/to/page.html]] or view the file at [[File1]] or reply at [[REPLY]] or OptOut at [[STOP]] | An example Message that uses the URL Shortener, File Link, Reply Link and Unsubscribe functions | |
Destinations | > Recipient | +6421000001 | Recipient of the SMS in E.164 internationalised format (for localized or friendly formatting, contact your account manager) |
> Attention | John Doe | Recipient's name | |
> First Name | John | Recipient's first name | |
> Last Name | Doe | Recipient's last name | |
> Company | Example Corp | Recipient's company | |
> Custom1 | Customisable tracking and personalisation field | ||
> Custom2 | Customisable tracking and personalisation field | ||
Files | > Name | File Name.pdf | Files referenced in [[File1]] commands (for MessageLink) |
> Data | %%Base-64%% | Base-64 encoded value of the attached file |
HTTP Method: POST
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
{
"MessageData" :
{
"Destinations" :
[
{ "Recipient" : "+6495005001" },
{ "Recipient" : "+6495005002" }
],
"Files":
[
{
"Name": "Sample.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
{
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"Resolution": "high",
"CSID": "Station ID",
"RetryAttempts": 3,
"RetryPeriod": 1,
"Message": "Hello,\r\nThis is a test message.\r\nThank you.",
"Destinations" :
[
{
"Recipient": "+6495005000",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "+6495005001" },
{ "Recipient": "+6495005002" },
{ "Recipient": "+6495005003" }
],
"Files":
[
{
"Name": "Sample.pdf",
"Data": "%%BASE-64 CONTENT%%"
},
{
"Name": "Sample2.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/fax \
--header "Content-Type: application/json; encoding='utf-8'" \
--header "Accept: application/json; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '{
"MessageData" :
{
"Destinations" :
[
{ "Recipient": "+6495005001" },
{ "Recipient": "+6495005002" }
],
"Files":
[
{
"Name": "Sample.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}'
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/fax \
--header "Content-Type: application/json; encoding='utf-8'" \
--header "Accept: application/json; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '{
"MessageData" :
{
"MessageID" : "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"Resolution": "high",
"CSID": "Station ID",
"Destinations" :
[
{
"Recipient": "+6495005000",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "+6495005001" },
{ "Recipient": "+6495005002" },
{ "Recipient": "+6495005003" }
],
"Files":
[
{
"Name": "Sample.pdf",
"Data": "%%BASE-64 CONTENT%%"
},
{
"Name": "Sample2.pdf",
"Data": "%%BASE-64 CONTENT%%"
}
]
}
}'
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
$authToken = "[Your Auth Token]";
$file1 = "Sample.pdf";
function GetBase64Contents($file_name)
{
// returns base64 encoded file data
if( file_exists($file_name) )
{
$fp = fopen($file_name,"r");
$file_content = fread($fp,filesize($file_name));
fclose($fp);
return base64_encode($file_content);
}
}
$data = array(
"MessageData" => array(
"Destinations" => array(
array(
"Recipient" => "+6495005001"
),
array(
"Recipient" => "+6495005002"
)
),
"Files" => array(
array(
"Name" => basename($file1),
"Data" => GetBase64Contents($file1)
)
),
)
);
$headers = array(
"Content-Type: application/json",
"Accept: application/json",
"encoding='utf-8'",
"Content-length: ".strlen(json_encode($data)),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/fax");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header('Content-Type: application/json');
echo $response;
break;
case "400": // error
case "401": // unauthorized
header('Content-Type: application/json');
echo $response;
break;
case "500": // critical error
echo $response;
echo $err;
break;
default:
echo $response;
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
function GetBase64Contents($file_name)
{
// returns base64 encoded file data
if( file_exists($file_name) )
{
$fp = fopen($file_name,"r");
$file_content = fread($fp,filesize($file_name));
fclose($fp);
return base64_encode($file_content);
}
}
$authToken = "[Your Auth Token]";
$message_id = "ID123456"; //optional
$file1 = "Sample1.pdf";
$file2 = "Sample2.pdf";
$data = array(
"MessageData" => array(
"MessageID" => $message_id,
"Reference" => "Test1",
"WebhookCallbackURL" => "https://www.example.com/webhook",
"WebhookCallbackFormat" => "JSON",
"SendTime" => "2022-08-01T09:00:00",
"TimeZone" => "New Zealand",
"SubAccount" => "SubAccount01",
"Department" => "Department01",
"ChargeCode" => "BillingGroup01",
"Resolution" => "high",
"CSID" => "Station ID",
"Destinations" => array(
array(
"Recipient" => "+6495005000",
"Attention" => "John Doe",
"First Name" => "John",
"Last Name" => "Doe",
"Company" => "Example Corp",
"Custom1" => "",
"Custom2" => ""
),
array( "Recipient" => "+6495005001" ),
array( "Recipient" => "+6495005002" ),
array( "Recipient" => "+6495005003" )
),
"Files" => array(
array(
"Name" => basename($file1),
"Data" => GetBase64Contents($file1)
),
array(
"Name" => basename($file2),
"Data" => GetBase64Contents($file2)
)
),
)
);
$headers = array(
"Content-Type: application/json",
"Accept: application/json",
"encoding='utf-8'",
"Content-length: ".strlen(json_encode($data)),
"Authorization: Basic {$authToken}",
"Connection: close"
);
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tnz.co.nz/api/v2.02/send/fax");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$err = "";
if(curl_errno($ch))
{
$err = curl_error($ch);
}
else
{
curl_close($ch);
}
switch( $info['http_code'] )
{
case "200": // success;
header('Content-Type: application/json');
echo $response;
break;
case "400": // error
case "401": // unauthorized
header('Content-Type: application/json');
echo $response;
break;
case "500": // critical error
echo $response;
echo $err;
break;
default:
echo $response;
echo $err;
break;
}
}
catch(Exception $e)
{
echo 'Caught exception: ', $e->getMessage();
}
?>
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
namespace TNZ
{
class Program
{
private static string GetFileName(string strFileLocation)
{
return System.IO.Path.GetFileName(strFileLocation);
}
private static string GetFileContents(string strFileLocation)
{
//
// Read files in bytes, convert to Base64String and return in string
//
using (FileStream reader = new FileStream(strFileLocation, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
string strContent = Convert.ToBase64String(buffer);
ASCIIEncoding encoding = new ASCIIEncoding();
return Encoding.ASCII.GetString(encoding.GetBytes(strContent));
}
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/fax";
string sender = "application@domain.com";
string api_key = "ta8wr7ymd";
string file1 = "D:\\File1.pdf";
string strJSONData = $@"{{
""Sender"": ""{sender}"",
""APIKey"": ""{api_key}"",
""MessageData"": {{
""Destinations"":
[
{{ ""Recipient"": ""+6495005001"" }},
{{ ""Recipient"": ""+6495005002"" }}
],
""Files"":
[
{{
""Name"": ""{GetFileName(file1)}"",
""Data"": ""{GetFileContents(file1)}""
}}
]
}}
}}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json; encoding='utf-8'";
byte[] byteArray = Encoding.UTF8.GetBytes(strJSONData);
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
using System;
using System.IO;
using System.Text;
using System.Net;
namespace TNZ
{
class Program
{
private static string GetFileName(string strFileLocation)
{
return System.IO.Path.GetFileName(strFileLocation);
}
private static string GetFileContents(string strFileLocation)
{
//
// Read files in bytes, convert to Base64String and return in string
//
using (FileStream reader = new FileStream(strFileLocation, FileMode.Open))
{
byte[] buffer = new byte[reader.Length];
reader.Read(buffer, 0, (int)reader.Length);
string strContent = Convert.ToBase64String(buffer);
ASCIIEncoding encoding = new ASCIIEncoding();
return Encoding.ASCII.GetString(encoding.GetBytes(strContent));
}
}
static void Main(string[] args)
{
string apiURL = "https://api.tnz.co.nz/api/v2.02/send/fax";
string authToken = "[Your Auth Token]";
string file1 = "D:\\File1.pdf";
string file2 = "D:\\File2.pdf";
string strJSONData = $@"{{
""MessageData"": {{
""MessageID"": ""ID123456"",
""Reference"": ""Test1"",
""WebhookCallbackURL"": ""https://www.example.com/webhook"",
""WebhookCallbackFormat"": ""JSON"",
""SendTime"": ""2022-08-01T09:00:00"",
""TimeZone"": ""New Zealand"",
""SubAccount"": ""SubAccount01"",
""Department"": ""Department01"",
""ChargeCode"": ""BillingGroup01"",
""Resolution"": ""High"",
""CSID"": ""Station ID"",
""Destinations"":
[
{{
""Recipient"": ""+6495005000"",
""Attention"": ""John Doe"",
""First Name"": ""John"",
""Last Name"": ""Doe"",
""Company"": ""Example Corp"",
""Custom1"": """",
""Custom2"": """"
}},
{{ ""Recipient"": ""+6495005001"", ""Attention"": ""Recipient 2"" }},
{{ ""Recipient"": ""+6495005002"" }},
{{ ""Recipient"": ""+6495005003"" }}
],
""Files"":
[
{{
""Name"": ""{GetFileName(file1)}"",
""Data"": ""{GetFileContents(file1)}""
}},
{{
""Name"": ""{GetFileName(file2)}"",
""Data"": ""{GetFileContents(file2)}""
}}
]
}}
}}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json; encoding='utf-8'";
request.Accept = "application/json; encoding='utf-8'";
request.Headers.Add("Authorization", $"Basic {authToken}");
byte[] byteArray = Encoding.UTF8.GetBytes(strJSONData);
request.ContentLength = byteArray.Length;
Stream newStream = request.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
string strResponse = "";
//
// More code to handle 400 Bad Request errors
//
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
strResponse = reader.ReadToEnd();
}
}
}
}
Console.WriteLine(strResponse);
Console.ReadLine();
}
}
}
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import base64
import json
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/fax"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
file_data = base64.b64encode(open("d:/File1.pdf","rb").read()).decode("utf-8")
data = {
"MessageData" :
{
"Destinations" :
[
{ "Recipient": "+6495005001" },
{ "Recipient": "+6495005002" }
],
"Files" :
[
{
"Name": "File1.pdf",
"Data": file_data
}
]
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
print(r.text)
{
"Result": "Success",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD"
}
{
"Result": "Failed",
"MessageID": "AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/json; encoding='utf-8'"
Accept="application/json; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
import requests
import base64
import json
authToken = "[Your Auth Token]"
url = "https://api.tnz.co.nz/api/v2.02/send/fax"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Basic {authToken}",
"encoding": "utf-8"
}
file_data = base64.b64encode(open("d:/File1.pdf","rb").read()).decode("utf-8")
data = {
"MessageData" :
{
"MessageID": "ID123456",
"Reference": "Test1",
"WebhookCallbackURL": "https://www.example.com/webhook",
"WebhookCallbackFormat": "JSON",
"SendTime": "2022-08-01T09:00:00",
"TimeZone": "New Zealand",
"SubAccount": "SubAccount01",
"Department": "Department01",
"ChargeCode": "BillingGroup01",
"Resolution": "high",
"CSID": "Station ID",
"Destinations" :
[
{
"Recipient": "+6495005000",
"Attention": "John Doe",
"First Name": "John",
"Last Name": "Doe",
"Company": "Example Corp",
"Custom1": "",
"Custom2": ""
},
{ "Recipient": "+6495005001" },
{ "Recipient": "+6495005002" },
{ "Recipient": "+6495005003" }
],
"Files" :
[
{
"Name": "File1.pdf",
"Data": file_data
}
]
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
print(r.text)
{
"Result": "Success",
"MessageID": "ID123456"
}
{
"Result": "Failed",
"MessageID": "ID123456",
"ErrorMessage": "Missing Sender"
}
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?xml version="1.0" encoding="UTF-8"?>
<FaxRequest>
<MessageData>
<Destinations>
<Destination><Recipient>+6495005001</Recipient></Destination>
<Destination><Recipient>+6495005002</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</FaxRequest>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</Message>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?xml version="1.0" encoding="UTF-8"?>
<FaxRequest>
<MessageData>
<MessageID>ID123456</MessageID>
<Reference>Test1</Reference>
<WebhookCallbackURL>https://www.example.com/webhook</Reference>
<WebhookCallbackFormat>XML</Reference>
<SendTime>2022-08-01T09:00:00</SendTime>
<TimeZone>New Zealand</TimeZone>
<SubAccount>SubAccount01</SubAccount>
<Department>Department01</Department>
<ChargeCode>BillingGroup01</ChargeCode>
<Resolution>High</Resolution>
<CSID>Station ID</CSID>
<Destinations>
<Destination>
<Recipient>+6495005000</Recipient>
<Attention>John Doe</Attention>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Company>Example Corp</Company>
<Custom1></Custom1>
<Custom2></Custom2>
</Destination>
<Destination><Recipient>+6495005001</Recipient></Destination>
<Destination><Recipient>+6495005002</Recipient></Destination>
<Destination><Recipient>+6495005003</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
<File>
<Name>Sample2.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</FaxRequest>
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</Message>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/fax \
--header "Content-Type: application/xml; encoding='utf-8'" \
--header "Accept: application/xml; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '<?xml version="1.0" encoding="UTF-8"?>
<FaxRequest>
<MessageData>
<Destinations>
<Destination><Recipient>+6495005001</Recipient></Destination>
<Destination><Recipient>+6495005002</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</FaxRequest>'
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>AAAAAAAA-BBBB-BBBB-CCCC-DDDDDDDDDDDD</MessageID>
<ErrorMessage>Missing or empty sender</Message>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
curl --request POST \
--url https://api.tnz.co.nz/api/v2.02/send/fax \
--header "Content-Type: application/xml; encoding='utf-8'" \
--header "Accept: application/xml; encoding='utf-8'" \
--header "Authorization: Basic [Your Auth Token]" \
--data '<?xml version="1.0" encoding="UTF-8"?>
<FaxRequest>
<MessageData>
<MessageID>ID123456</MessageID>
<WebhookCallbackURL>https://www.example.com/webhook</Reference>
<WebhookCallbackFormat>XML</Reference>
<Reference>Test1</Reference>
<SendTime>2022-08-01T09:00:00</SendTime>
<TimeZone>New Zealand</TimeZone>
<SubAccount>SubAccount01</SubAccount>
<Department>Department01</Department>
<ChargeCode>BillingGroup01</ChargeCode>
<Resolution>High</Resolution>
<CSID>Station ID</CSID>
<Destinations>
<Destination>
<Recipient>+6495005000</Recipient>
<Attention>John Doe</Attention>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Company>Example Corp</Company>
<Custom1></Custom1>
<Custom2></Custom2>
</Destination>
<Destination><Recipient>+6495005001</Recipient></Destination>
<Destination><Recipient>+6495005002</Recipient></Destination>
<Destination><Recipient>+6495005003</Recipient></Destination>
</Destinations>
<Files>
<File>
<Name>Sample.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
<File>
<Name>Sample2.pdf</Name>
<Data>%%BASE-64 CONTENT%%</Data>
</File>
</Files>
</MessageData>
</FaxRequest>'
<?xml version="1.0"?>
<root>
<Result>Success</Result>
<MessageID>ID123456</MessageID>
</root>
<?xml version="1.0"?>
<root>
<Result>Failed</Result>
<MessageID>ID123456</MessageID>
<ErrorMessage>Missing or empty sender</Message>
</root>
API URL: https://api.tnz.co.nz/api/v2.02/send/fax
HTTP Method: POST
HTTP Headers: Content-Type="application/xml; encoding='utf-8'"
Accept="application/xml; encoding='utf-8'"
Authorization="Basic [Your Auth Token]"
<?php
class SimpleXMLExtended extends SimpleXMLElement {
//
// this class extends SimplXMLElement to insert CDATA if necessary.
// for example, XML is not validated if HTML tag is inside XML Element,
// so we want to wrap inside CDATA, ...