Fully featured email

This method allows you to send one or more email message with attachments to one or more destination addresses.

Resource

https://api.infobip.com/email/1/send

Parameters

Property name Type Description
from string Email address with optional sender name. Example: "Jane Doe <jane.doe@somecompany.com>"
to string Email address of the recipients with optional placeholder values for personalized content.
replyTo string Email address to which recipients of the email can reply
subject string Message subject
text string Body of the message
html string HTML body of the message. If html and text fields are present, text field will be ignored and html will be delivered as message body
templateId int Template identifier based on which the email message is generated. The template is created over Infobip Portal. If templateId is present then html and text values are ignored.
defaultPlaceholders string Default placeholder values used for all recipients. The values are used to generate the email message.
attachment file File attachment
bulkId string The ID uniquely identifies the sent Email request. This filter will enable you to query delivery reports for all the messages using just one request. You will receive a bulkId in the response after sending an Email request. If you don't set your own bulkId, unique ID will be generated by our system and returned in the API response.
sendAt datetime Date and time when the message is to be sent. Used for scheduled Email (Email is not sent immediately, but at scheduled time).
intermediateReport boolean The real-time Intermediate delivery report that will be sent on your callback server. Can be true or false.
notifyUrl string The URL on your callback server on which the Delivery report will be sent.
notifyContentType string Preferred Delivery report content type. Can be application/json or application/xml.
callbackData string Additional client's data that will be sent on the notifyUrl. The maximum value is 200 characters.
track boolean Enable or disable open and click tracking. Can be true or false.Default value is false. Passing true will only enable tracking and the statistics would be visible in web portal interface alone.
trackingUrl string The URL on your callback server on which the open and click notifications will be sent. If you are passing this parameter then track=true will be assigned, you don't need to pass track=true separately. See the section "Tracking Notifications" below for details.

Request Example

					curl -s --user user:password \
https://api.infobip.com/email/1/send \
-F from='Jane Smith <jane.smith@somecompany.com>' \
-F to='john.smith@somedomain.com' \
-F replyTo='all.replies@somedomain.com' \
-F subject='Mail subject text' \
-F text='Mail body text' \
--form-string html='<h1>Html body</h1><p>Rich HTML message body.</p>' \
-F attachment=@files/image1.jpg \
-F bulkId='cusotmBulkId' \
-F intermediateReport='true' \
-F notifyUrl='https://www.example.com/email/advanced' \
-F notifyContentType = 'application/json' \
-F callbackData = 'DLR callback data'
					
				
					POST /email/1/send HTTP/1.1
Host: api.infobip.com
Authorization: Basic bWt1dGljMjpNdTtpMjAxMiws
Accept: application/json
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="from"

Jane Doe <jane.doe@somecompany.com>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to"

john.smith@somecompany.com

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="replyTo"

all.replies@somedomain.com
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="subject"

Test mail subject
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="text"

Simple text body
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="html"

<h1>Html body</h1><p>Rich HTML message body.</p>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="attachment"; filename="image1.jpg"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="bulkId"

A_CUSTOM_BULK_ID
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="intermediateReport" 
true

------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="notifyUrl" 
https://www.example.com/email/advanced

------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="notifyContentType" 
application/json

------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="callbackData" 
DLR callback data

------WebKitFormBoundary7MA4YWxkTrZu0gW--
					
				
					<?php
define('MULTIPART_BOUNDARY', '----'.md5(time()));
define('EOL',"\r\n");// PHP_EOL cannot be used for emails we need the CRFL '\r\n'

function getBodyPart($FORM_FIELD, $value) {
    if ($FORM_FIELD === 'attachment') {
        $content = 'Content-Disposition: form-data; name="'.$FORM_FIELD.'"; filename="'.basename($value).'"' . EOL;
        $content .= 'Content-Type: '.mime_content_type($value) . EOL;
        $content .= 'Content-Transfer-Encoding: binary' . EOL;
        $content .= EOL . file_get_contents($value) .EOL;
    } else {
        $content = 'Content-Disposition: form-data; name="' . $FORM_FIELD . '"' . EOL;
        $content .= EOL . $value . EOL;
    }

    return $content;
}

/*
 * Method to convert an associative array of parameters into the HTML body string
*/
function getBody($fields) {
    $content = '';
    foreach ($fields as $FORM_FIELD => $value) {
        $values = is_array($value) ? $value : array($value);
        foreach ($values as $v) {
            $content .= '--' . MULTIPART_BOUNDARY . EOL . getBodyPart($FORM_FIELD, $v);
        }
    }
    return $content . '--' . MULTIPART_BOUNDARY . '--'; // Email body should end with "--"
}

/*
 * Method to get the headers for a basic authentication with username and passowrd
*/
function getHeader($username, $password){
    // basic Authentication
    $auth = base64_encode("$username:$password");

    // Define the header
    return array('Authorization:Basic '.$auth, 'Content-Type: multipart/form-data ; boundary=' . MULTIPART_BOUNDARY );
}

// URL to the API that sends the email.
$url = 'https://api.infobip.com/email/1/send';

// Associate Array of the post parameters to be sent to the API
$postData = array(
    'from' => 'company@somecompany.com',
    'to' => 'john.smith@somedomain.com',
  	'replyTo' => 'all.replies@somedomain.com',
    'subject' => 'Mail subject text',
    'text' => 'Mail body text',
    'html' => '

Html body

Rich HTML message body.

', 'attachment' => '/path/to/file/image1.jpg' 'intermediateReport'=> 'true' 'notifyUrl' => 'https://www.example.com/email/advanced' 'notifyContentType' => 'application/json' 'callbackData' => 'DLR callback data' ); // Create the stream context. $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => getHeader('username', 'password'), 'content' => getBody($postData), ) )); // Read the response using the Stream Context. $response = file_get_contents($url, false, $context); ?>
					/*----Sending fully featured email----*/

function createFormData(data) {
    var formData = new FormData();
    for (var key in data) {
        formData.append(key, data[key]);
    }
    return formData;
}

//Dummy File Object
var file = new File([""], "filename");

var data = {
    'from': 'Sender Name <from@example.com>',
    'to': 'recipient1@example.com',
    'subject': 'Test Subject',
    'html': '<h1>Html body</h1><p>Rich HTML message body.</p>',
    'text': 'Sample Email Body',
    'attachment': file,
    'intermediateReport': 'true',
    'notifyUrl': 'https://www.example.com/email/advanced'
};


var xhr = new XMLHttpRequest();
xhr.withCredentials = false;

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open('POST', 'https://api.infobip.com/email/1/send', false);
xhr.setRequestHeader('authorization', 'Basic bWt1dGljMjpNdTtpMjAxMiws');
xhr.setRequestHeader('accept', 'application/json');

xhr.send(createFormData(data));
					
				
					HttpResponse<String> response = Unirest.post("https://api.infobip.com/email/1/send")
                .header("Authorization", "Basic YXJhamhhbnNhOmF4ZGNmcnQy")
                .header("Accept", "application/json")
                .field("from", "Jane Smith <jane.smith@somecompany.com>", "text/plain")
                .field("to", "john.smith@somedomain.com", "text/plain")
                .field("replyTo", "all.replies@somedomain.com", "text/plain")
                .field("subject", "Mail subject text", "text/plain")
                .field("text", "Mail body text", "text/plain")
                .field("html", "<h1>Html body</h1><p>Rich HTML message body.</p>", "text/plain")
                .field("attachment", new File("/tmp/image1.png"))
                .field("bulkId", "cusotmBulkId","text/plain")
                .field("intermediateReport", "true", "text/plain")
                .field("notifyUrl", "https://www.example.com/email/advanced", "text/plain")
                .field("notifyContentType", "application/json", "text/plain")
                .field("callbackData", "DLR callback data", "text/plain")
                .asString();
					
				
					HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://api.infobip.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "dJKDndiasdf797899ar4rkn2FtS0BiQGRkIQ");
            var request = new MultipartFormDataContent();            
            request.Add(new StreamContent(File.OpenRead(filePath)), "attachment", new FileInfo(filePath).Name);
            request.Add(new StringContent("Jane Doe <jane.doe@somecompany.com>"), "from");
            request.Add(new StringContent("john.smith@somedomain.com"), "to");
            request.Add(new StringContent("all.replies@somedomain.com"), "replyto");
            request.Add(new StringContent("Mail subject text"), "subject");
            request.Add(new StringContent("Rich HTML message body."), "text");
            request.Add(new StringContent("<h1>Html body</h1><p>Rich HTML message body.</p>"), "html");
            request.Add(new StringContent("cusotmBulkId"), "bulkId");
            request.Add(new StringContent("true"), "intermediateReport");
            request.Add(new StringContent("https://www.example.com/email/advanced"), "notifyUrl");
            request.Add(new StringContent("application/json"), "notifyContentType");
            request.Add(new StringContent("DLR callback data"), "callbackData");            
	    var response = client.PostAsync("email/1/send", request).Result;
            if (response.IsSuccessStatusCode) {
                var responseContent = response.Content;
                string responseString = responseContent.ReadAsStringAsync().Result;
                Console.WriteLine(responseString);
            }
					
				

Response

					{
  "bulkId": "cusotmBulkId",
  "messages": [
    {
      "to": "jane.smith@somecompany.com",
      "messageCount": 1,
      "messageId": "c268350e-c85e-41d1-b5a0-a60771b134bd",
      "status": {
        "groupId": 1,
        "groupName": "PENDING",
        "id": 7,
        "name": "PENDING_ENROUTE",
        "description": "Message sent to next instance"
      }
    }
  ]
}
					
				

Response format

When successful, the response header HTTP status code will be 200 OK and the message will be sent.

If you try to send message without authorization, you will receive the 401 Unauthorized error.

Response

Parameter Type Description
bulkId String Either a user provided custom bulk id or an auto generated one in case bulkId was absent in the request.
messages MessageInfo Array of sent message objects, one object per every message.

MessageInfo

Parameter Type Description
to String The message destination address.
status Status Indicates whether the message is successfully sent, not sent, delivered, not delivered, waiting for delivery or any other possible status.
messageCount int The number of sent message segments.
messageId String The ID that uniquely identifies the message sent.

Status

Parameter Type Description
groupId int Status group ID.
groupName String Status group name.
id int Status ID.
name String Status name.
description String Human-readable description of the status.
action String Action that should be taken to eliminate the error.

Send email to multiple recipients

You can easily send the same email to multiple recipient addresses by including more than one to parameters in the request.

Example

Request:

curl -s --user user:password \
https://api.infobip.com/email/1/send \
-F from='Jane Smith <jane.smith@somecompany.com>' \
-F to='john.smith@somedomain.com' \
-F to='tom.smith@somedomain.com' \
-F subject='Mail subject text' \
-F text='Mail body text' \
--form-string html='<h1>Html body</h1><p>Rich HTML message body.</p>' \
-F attachment=@files/image1.jpg
POST /email/1/send HTTP/1.1
Host: api.infobip.com
Authorization: Basic bWt1dGljMjpNdTtpMjAxMiws
Accept: application/json
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="from"

Jane Doe <jane.doe@somecompany.com>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to"

john.smith@somecompany.com
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to"

jane.smith@somecompany.com
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="subject"

Test mail subject
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="text"

Simple text body
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="html"

<h1>Html body</h1><p>Rich HTML message body.</p>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="attachment"; filename="image1.jpg"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundary7MA4YWxkTrZu0gW--
<?php
define('MULTIPART_BOUNDARY', '----'.md5(time()));
define('EOL',"\r\n");// PHP_EOL cannot be used for emails we need the CRFL '\r\n'

function getBodyPart($FORM_FIELD, $value) {
    if ($FORM_FIELD === 'attachment') {
        $content = 'Content-Disposition: form-data; name="'.$FORM_FIELD.'"; filename="'.basename($value).'"' . EOL;
        $content .= 'Content-Type: '.mime_content_type($value) . EOL;
        $content .= 'Content-Transfer-Encoding: binary' . EOL;
        $content .= EOL . file_get_contents($value) .EOL;
    } else {
        $content = 'Content-Disposition: form-data; name="' . $FORM_FIELD . '"' . EOL;
        $content .= EOL . $value . EOL;
    }

    return $content;
}

/*
 * Method to convert an associative array of parameters into the HTML body string
*/
function getBody($fields) {
    $content = '';
    foreach ($fields as $FORM_FIELD => $value) {
        $values = is_array($value) ? $value : array($value);
        foreach ($values as $v) {
            $content .= '--' . MULTIPART_BOUNDARY . EOL . getBodyPart($FORM_FIELD, $v);
        }
    }
    return $content . '--' . MULTIPART_BOUNDARY . '--'; // Email body should end with "--"
}

/*
 * Method to get the headers for a basic authentication with username and passowrd
*/
function getHeader($username, $password){
    // basic Authentication
    $auth = base64_encode("$username:$password");

    // Define the header
    return array('Authorization:Basic '.$auth, 'Content-Type: multipart/form-data ; boundary=' . MULTIPART_BOUNDARY );
}

// URL to the API that sends the email.
$url = 'https://api.infobip.com/email/1/send';

// Associate Array of the post parameters to be sent to the API
$postData = array(
    'from' => 'company@somecompany.com',
    'to' => array('john.smith@somedomain.com', 'jane.smith@somedomain.com'),
    'subject' => 'Mail subject text',
    'text' => 'Mail body text',
    'html' => '<h1>Html body</h1><p>Rich HTML message body.</p>',
    'attachment' => '/path/to/file/image1.jpg'
);

// Create the stream context.
$context = stream_context_create(array(
    'http' => array(
          'method' => 'POST',
          'header' => getHeader('username', 'password'),
          'content' =>  getBody($postData),
    )
));

// Read the response using the Stream Context.
$response = file_get_contents($url, false, $context);
 ?>
/*----Sending email to multiple recipients----*/

function isArray(elem) {
    return Object.prototype.toString.call(elem) === '[object Array]';
}

function createFormData(data) {
    var formData = new FormData();
    for (var key in data) {
        if (isArray(data[key])) {
            for (var key2 in data[key]) {
                formData.append(key, data[key][key2]);
            }
        } else {
            formData.append(key, data[key]);
        }
    }
    return formData;
}

//Dummy File Object
var file = new File([""], "filename");

var data = {
    'from': 'Sender Name <from@example.com>',
    'to': ['recipient1@example.com', 'recipient2@example.com', 'invalid,@example.com'],
    'subject': 'Test Subject',
    'html': '<h1>Html body</h1><p>Rich HTML message body.</p>',
    'text': 'Sample Email Body',
    'attachment': file,
    'intermediateReport': 'true',
    'notifyUrl': 'http://www.example.com/email/advanced'
};


var xhr = new XMLHttpRequest();
xhr.withCredentials = false;

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open('POST', 'https://api.infobip.com/email/1/send', false);
xhr.setRequestHeader('authorization', 'Basic bWt1dGljMjpNdTtpMjAxMiws');
xhr.setRequestHeader('accept', 'application/json');

xhr.send(createFormData(data));
HttpResponse<String> response = Unirest.post("\"https://api.infobip.com/email/1/send")
                .header("Authorization", "Basic YXJhamhhbnNhOmF4ZGNmcnQy")
                .header("Accept", "application/json")
                .field("from", "Jane Smith <jane.smith@somecompany.com>", "text/plain")
                .field("to", "john.smith@somedomain.com", "text/plain")
                .field("to", "tom.smith@somedomain.com", "text/plain")
                .field("subject", "Mail subject text", "text/plain")
                .field("text", "Mail body text", "text/plain")
                .field("html", "<h1>Html body</h1><p>Rich HTML message body.</p>", "text/plain")
                .field("attachment", new File("/tmp/image1.png"))
                .asString();

Response:

{
  "bulkId": "lrzkq6gatdkxouhrkgni",
  "messages": [
    {
      "to": "john.smith@somecompany.com",
      "messageCount": 1,
      "messageId": "9129e972-be85-49ed-b0e9-f51fbd2b27c0",
      "status": {
        "groupId": 1,
        "groupName": "PENDING",
        "id": 7,
        "name": "PENDING_ENROUTE",
        "description": "Message sent to next instance"
      }
    },
    {
      "to": "tom.smith@somecompany.com",
      "messageCount": 1,
      "messageId": "cd0c5682-42e2-481a-be95-15ed72450646",
      "status": {
        "groupId": 1,
        "groupName": "PENDING",
        "id": 7,
        "name": "PENDING_ENROUTE",
        "description": "Message sent to next instance"
      }
    }
  ]
}	
  

Send email with multiple attachments

Sending email with more than one attachment is done by adding multiple attachment parameters in the request.

Example

Request:

curl -s --user user:password \
https://api.infobip.com/email/1/send \
-F from='Jane Smith <jane.smith@somecompany.com>' \
-F to='john.smith@somedomain.com' \
-F subject='Mail subject text' \
-F text='Mail body text' \
--form-string html='<h1>Html body</h1><p>Rich HTML message body.</p>' \
-F attachment=@files/image1.jpg
-F attachment=@files/image2.jpg
POST /email/1/send HTTP/1.1
Host: api.infobip.com
Authorization: Basic bWt1dGljMjpNdTtpMjAxMiws
Accept: application/json
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="from"

Jane Doe <jane.doe@somecompany.com>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to"

john.smith@somecompany.com
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="subject"

Test mail subject
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="text"

Simple text body
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="html"

<h1>Html body</h1><p>Rich HTML message body.</p>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="attachment"; filename="image1.jpg"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="attachment"; filename="image2.jpg"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundary7MA4YWxkTrZu0gW--
<?php
define('MULTIPART_BOUNDARY', '----'.md5(time()));
define('EOL',"\r\n");// PHP_EOL cannot be used for emails we need the CRFL '\r\n'

function getBodyPart($FORM_FIELD, $value) {
    if ($FORM_FIELD === 'attachment') {
        $content = 'Content-Disposition: form-data; name="'.$FORM_FIELD.'"; filename="'.basename($value).'"' . EOL;
        $content .= 'Content-Type: '.mime_content_type($value) . EOL;
        $content .= 'Content-Transfer-Encoding: binary' . EOL;
        $content .= EOL . file_get_contents($value) .EOL;
    } else {
        $content = 'Content-Disposition: form-data; name="' . $FORM_FIELD . '"' . EOL;
        $content .= EOL . $value . EOL;
    }

    return $content;
}

/*
 * Method to convert an associative array of parameters into the HTML body string
*/
function getBody($fields) {
    $content = '';
    foreach ($fields as $FORM_FIELD => $value) {
        $values = is_array($value) ? $value : array($value);
        foreach ($values as $v) {
            $content .= '--' . MULTIPART_BOUNDARY . EOL . getBodyPart($FORM_FIELD, $v);
        }
    }
    return $content . '--' . MULTIPART_BOUNDARY . '--'; // Email body should end with "--"
}

/*
 * Method to get the headers for a basic authentication with username and passowrd
*/
function getHeader($username, $password){
    // basic Authentication
    $auth = base64_encode("$username:$password");

    // Define the header
    return array('Authorization:Basic '.$auth, 'Content-Type: multipart/form-data ; boundary=' . MULTIPART_BOUNDARY );
}

// URL to the API that sends the email.
$url = 'https://api.infobip.com/email/1/send';

// Associate Array of the post parameters to be sent to the API
$postData = array(
    'from' => 'company@somecompany.com',
    'to' => 'john.smith@somedomain.com',
    'subject' => 'Mail subject text',
    'text' => 'Mail body text',
    'html' => '<h1>Html body</h1><p>Rich HTML message body.</p>',
    'attachment' => array('/path/to/file/image1.jpg', '/path/to/file/image2.jpg')
);

// Create the stream context.
$context = stream_context_create(array(
    'http' => array(
          'method' => 'POST',
          'header' => getHeader('username', 'password'),
          'content' =>  getBody($postData),
    )
));

// Read the response using the Stream Context.
$response = file_get_contents($url, false, $context);
 ?>

/*----Sending email with multiple attachments----*/

function isArray(elem) {
    return Object.prototype.toString.call(elem) === '[object Array]';
}

function createFormData(data) {
    var formData = new FormData();
    for (var key in data) {
        if (isArray(data[key])) {
            for (var key2 in data[key]) {
                formData.append(key, data[key][key2]);
            }
        } else {
            formData.append(key, data[key]);
        }
    }
    return formData;
}

//Dummy File Objects
var file1 = new File([""], "filename1");
var file2 = new File([""], "filename2");

var data = {
    'from': 'Sender Name <from@example.com>',
    'to': 'recipient@example.com',
    'subject': 'Test Subject',
    'html': '<h1>Html body</h1><p>Rich HTML message body.</p>',
    'text': 'Sample Email Body',
    'attachment': [file1, file2],
    'intermediateReport': 'true',
    'notifyUrl': 'http://www.example.com/email/advanced'
};


var xhr = new XMLHttpRequest();
xhr.withCredentials = false;

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open('POST', 'https://api.infobip.com/email/1/send', false);
xhr.setRequestHeader('authorization', 'Basic bWt1dGljMjpNdTtpMjAxMiws');
xhr.setRequestHeader('accept', 'application/json');

xhr.send(createFormData(data));
HttpResponse<String> response = Unirest.post("\"https://api.infobip.com/email/1/send")
                .header("Authorization", "Basic YXJhamhhbnNhOmF4ZGNmcnQy")
                .header("Accept", "application/json")
                .field("from", "Jane Smith <jane.smith@somecompany.com>", "text/plain")
                .field("to", "john.smith@somedomain.com", "text/plain")
                .field("subject", "Mail subject text", "text/plain")
                .field("text", "Mail body text", "text/plain")
                .field("html", "<h1>Html body</h1><p>Rich HTML message body.</p>", "text/plain")
                .field("attachment", new File("/tmp/image1.png"))
                .field("attachment", new File("/tmp/image2.png"))
                .asString();

Response:

{
  "messages": [
    {
      "to": "john.smith@somecompany.com",
      "messageCount": 1,
      "messageId": "c268350e-c85e-41d1-b5a0-a60771b134bd",
      "status": {
        "groupId": 1,
        "groupName": "PENDING",
        "id": 7,
        "name": "PENDING_ENROUTE",
        "description": "Message sent to next instance"
      }
    }
  ]
}	
  

Send personalized emails using templates

You can send personalized emails by adding placeholder values within the to parameter of the request. If you want send the message based on a previously defined template, pass the template identifier value in the templateId parameter. To manage Templates login to Infobip Portal web interface.

Example

Request:

curl -s --user user:password \
https://api.infobip.com/email/1/send \
-F from='Jane Smith <jane.smith@somecompany.com>' \
-F to='{"to": "john.smith@somedomain.com", "placeholders": { "firstname": "John", "lastname":"Smith"}}' \
-F to='tom.smith@somedomain.com' \
-F subject='Mail subject text' \
-F templateId='12345' \
-F defaultPlaceholders='{ "firstname": "Customer"}}' \
-F attachment=@files/image1.jpg
POST /email/1/send HTTP/1.1
Host: api.infobip.com
Authorization: Basic bWt1dGljMjpNdTtpMjAxMiws
Accept: application/json
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="from"

Jane Doe <jane.doe@somecompany.com>
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to"

'to={"to": "john.smith@somedomain.com", "placeholders": { "firstname": "John", "lastname": "Smith"}}' \
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to"

tom.smith@somecompany.com
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="subject"

Test mail subject
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="templateId"

12345
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="defaultPlaceholders"

{ "firstname": "Customer"}}' \
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="attachment"; filename="image1.jpg"
Content-Type: application/x-object

... contents of file goes here ...
------WebKitFormBoundary7MA4YWxkTrZu0gW--
<?php
define('MULTIPART_BOUNDARY', '----'.md5(time()));
define('EOL',"\r\n");// PHP_EOL cannot be used for emails we need the CRFL '\r\n'

function getBodyPart($FORM_FIELD, $value) {
    if ($FORM_FIELD === 'attachment') {
        $content = 'Content-Disposition: form-data; name="'.$FORM_FIELD.'"; filename="'.basename($value).'"' . EOL;
        $content .= 'Content-Type: '.mime_content_type($value) . EOL;
        $content .= 'Content-Transfer-Encoding: binary' . EOL;
        $content .= EOL . file_get_contents($value) .EOL;
    } else {
        $content = 'Content-Disposition: form-data; name="' . $FORM_FIELD . '"' . EOL;
        $content .= EOL . $value . EOL;
    }

    return $content;
}

/*
 * Method to convert an associative array of parameters into the HTML body string
*/
function getBody($fields) {
    $content = '';
    foreach ($fields as $FORM_FIELD => $value) {
        $values = is_array($value) ? $value : array($value);
        foreach ($values as $v) {
            $content .= '--' . MULTIPART_BOUNDARY . EOL . getBodyPart($FORM_FIELD, $v);
        }
    }
    return $content . '--' . MULTIPART_BOUNDARY . '--'; // Email body should end with "--"
}

/*
 * Method to get the headers for a basic authentication with username and passowrd
*/
function getHeader($username, $password){
    // basic Authentication
    $auth = base64_encode("$username:$password");

    // Define the header
    return array('Authorization:Basic '.$auth, 'Content-Type: multipart/form-data ; boundary=' . MULTIPART_BOUNDARY );
}

// URL to the API that sends the email.
$url = 'https://api.infobip.com/email/1/send';

// Associate Array of the post parameters to be sent to the API
$postData = array(
    'from' => 'jane.doe@somecompany.com',
    'to' => array('to={"to": "john.smith@somedomain.com", "placeholders": { "firstname": "John", "lastname": "Smith"}}' \, 'tom.smith@somedomain.com'),
    'subject' => 'Mail subject text',
    'templateId' => 12345,
    'defaultPlaceholders' => { "firstname": "Customer"}}' \,
    'attachment' => '/path/to/file/image1.jpg'
);


// Create the stream context.
$context = stream_context_create(array(
    'http' => array(
          'method' => 'POST',
          'header' => getHeader('username', 'password'),
          'content' =>  getBody($postData),
    )
));

// Read the response using the Stream Context.
$response = file_get_contents($url, false, $context);
 ?>
/*----Sending email to multiple recipients----*/

function isArray(elem) {
    return Object.prototype.toString.call(elem) === '[object Array]';
}

function createFormData(data) {
    var formData = new FormData();
    for (var key in data) {
        if (isArray(data[key])) {
            for (var key2 in data[key]) {
                formData.append(key, data[key][key2]);
            }
        } else {
            formData.append(key, data[key]);
        }
    }
    return formData;
}

//Dummy File Object
var file = new File([""], "filename");

var data = {
    'from': 'Sender Name <from@example.com>',
    'to': ['to={"to": "john.smith@somedomain.com", "placeholders": { "firstname": "John", "lastname": "Smith"}}' \, 'tom.smith@somedomain.com'],
    'subject': 'Test Subject',
    'templateId': 12345,
    'defaultPlaceholders': { "firstname": "Customer"}}' \,
    'attachment': file,
    'intermediateReport': 'true',
    'notifyUrl': 'http://www.example.com/email/advanced'
};


var xhr = new XMLHttpRequest();
xhr.withCredentials = false;

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open('POST', 'https://api.infobip.com/email/1/send', false);
xhr.setRequestHeader('authorization', 'Basic bWt1dGljMjpNdTtpMjAxMiws');
xhr.setRequestHeader('accept', 'application/json');

xhr.send(createFormData(data));
HttpResponse<String> response = Unirest.post("\"https://api.infobip.com/email/1/send")
                .header("Authorization", "Basic YXJhamhhbnNhOmF4ZGNmcnQy")
                .header("Accept", "application/json")
                .field("from", "Jane Smith <jane.smith@somecompany.com>", "text/plain")
                .field("to", "john.smith@somedomain.com", "placeholders": { "firstname": "John", "lastname": "Smith"}}' \, "text/plain")
                .field("to", "tom.smith@somedomain.com", "text/plain")
                .field("subject", "Mail subject text", "text/plain")
                .field("templateId", "12345", "text/plain")
                .field("defaultPlaceholders", "{ "firstname": "Customer"}}' \", "text/plain")
                .field("attachment", new File("/tmp/image1.png"))
                .asString();

Response:

{
  "bulkId": "lrzkq6gatdkxouhrkgni",
  "messages": [
    {
      "to": "john.smith@somecompany.com",
      "messageCount": 1,
      "messageId": "9129e972-be85-49ed-b0e9-f51fbd2b27c0",
      "status": {
        "groupId": 1,
        "groupName": "PENDING",
        "id": 7,
        "name": "PENDING_ENROUTE",
        "description": "Message sent to next instance"
      }
    },
    {
      "to": "tom.smith@somecompany.com",
      "messageCount": 1,
      "messageId": "cd0c5682-42e2-481a-be95-15ed72450646",
      "status": {
        "groupId": 1,
        "groupName": "PENDING",
        "id": 7,
        "name": "PENDING_ENROUTE",
        "description": "Message sent to next instance"
      }
    }
  ]
}	
  

Tracking Notifications

If trackingUrl is passed, you will be notified whever the email is opened or an URL in the email is clicked by recipient. The structure of the data passed in the open and click notifications is shown below.

Open Notifications:
{
"notificationType":"OPENED",
"domain":"sendingdomain.com",
"recipient":"john.smith@somecompany.com",
"sendDateTime":1517652288663,
"messageId":"zl3cf7frmy48ueavnnxy"
}	
  
Click Notifications:
{
"notificationType":"CLICKED",
"domain":"sendingdomain.com",
"recipient":"jane.smith@somecompany.com",
"url":"http://www.example.com/landingpage.html",
"sendDateTime":1517652288646,
"messageId":"zsf6q5vjgn1y6qqn65g7"
}