Send Email API


                    http://mail.themessaging.in/v2/email/send?apikey=94DAF66E-4DF6-4E8E-AF96-D094A8D21DF3&subject=&from=&fromName=&sender=&senderName=&msgFrom=&msgFromName=&replyTo=&replyToName=&to=&msgTo=&msgCC=&msgBcc=&lists=&segments=&mergeSourceFilename=&dataSource=&channel=&bodyHtml=&bodyText=&charset=&charsetBodyHtml=&charsetBodyText=&encodingType=&template=&headers_firstname=firstname: myValueHere&postBack=&merge_firstname=John&timeOffSetMinutes=&poolName=My Custom Pool&isTransactional=false&attachments=&trackOpens=true&trackClicks=true&utmSource=source1&utmMedium=medium1&utmCampaign=campaign1&utmContent=content1&bodyAmp=&charsetBodyAmp=

                    

Name Type Required? Default value Description
apikeystringYesApiKey that gives you access to our SMTP and HTTP API's. Available here.
attachmentsList of stringNonullNames or IDs of attachments previously uploaded to your account (via the File/Upload request) that should be sent with this e-mail.
bodyAmpstringNonullAMP email body
bodyHtmlstringNonullHtml email body
bodyTextstringNonullText email body
channelstringNonullAn ID field (max 191 chars) that can be used for reporting [will default to HTTP API or SMTP API]
charsetstringNonullText value of charset encoding for example: iso-8859-1, windows-1251, utf-8, us-ascii, windows-1250 and more
charsetBodyAmpstringNonullSets charset for body AMP MIME part (overrides default value from charset parameter)
charsetBodyHtmlstringNonullSets charset for body html MIME part (overrides default value from charset parameter)
charsetBodyTextstringNonullSets charset for body text MIME part (overrides default value from charset parameter)
dataSourcestringNonullName or ID of the previously uploaded file (via the File/Upload request) which should be a CSV list of Recipients.
encodingTypeEncodingTypeNoApiTypes.EncodingType.None0 for None, 1 for Raw7Bit, 2 for Raw8Bit, 3 for QuotedPrintable, 4 for Base64 (Default), 5 for Uue note that you can also provide the text version such as "Raw7Bit" for value 1. NOTE: Base64 or QuotedPrintable is recommended if you are validating your domain(s) with DKIM.
fromstringNonullFrom email address
fromNamestringNonullDisplay name for from email address
headersRepeated list of string keys and string valuesNonullOptional Custom Headers. Request parameters prefixed by headers_ like headers_customheader1, headers_customheader2. Note: a space is required after the colon before the custom header value. headers_xmailer=xmailer: header-value1
isTransactionalbooleanNofalseTrue, if email is transactional (non-bulk, non-marketing, non-commercial). Otherwise, false
listsList of stringNonullThe name of a contact list you would like to send to. Separate multiple contact lists by commas or semicolons.
mergeRepeated list of string keys and string valuesNonullRequest parameters prefixed by merge_ like merge_firstname, merge_lastname. If sending to a template you can send merge_ fields to merge data with the template. Template fields are entered with {firstname}, {lastname} etc.
mergeSourceFilenamestringNonullFile name one of attachments which is a CSV list of Recipients.
msgBccList of stringNonullOptional parameter. Will be ignored if the 'to' parameter is also provided. List of email recipients (each email is treated seperately). Separated by comma or semicolon.
msgCCList of stringNonullOptional parameter. Will be ignored if the 'to' parameter is also provided. List of email recipients (visible to all other recipients of the message as CC MIME header). Separated by comma or semicolon.
msgFromstringNonullOptional parameter. Sets FROM MIME header.
msgFromNamestringNonullOptional parameter. Sets FROM name of MIME header.
msgToList of stringNonullOptional parameter. Will be ignored if the 'to' parameter is also provided. List of email recipients (visible to all other recipients of the message as TO MIME header). Separated by comma or semicolon.
poolNamestringNonullName of your custom IP Pool to be used in the sending process
postBackstringNonullOptional header returned in notifications.
replyTostringNonullEmail address to reply to
replyToNamestringNonullDisplay name of the reply to address
segmentsList of stringNonullThe name of a segment you would like to send to. Separate multiple segments by comma or semicolon. Insert "0" for all Active contacts.
senderstringNonullEmail address of the sender
senderNamestringNonullDisplay name sender
subjectstringNonullEmail subject
templatestringNonullThe ID of an email template you have created in your account.
timeOffSetMinutesstringNonullNumber of minutes in the future this email should be sent up to a maximum of 1 year (524160 minutes)
toList of stringNonullList of email recipients (each email is treated separately, like a BCC). Separated by comma or semicolon. We suggest using the "msgTo" parameter if backward compatibility with API version 1 is not a must.
trackClicksbooleanNonullShould the clicks be tracked? If no value has been provided, Account's default setting will be used.
trackOpensbooleanNonullShould the opens be tracked? If no value has been provided, Account's default setting will be used.
utmCampaignstringNonullThe utm_campaign marketing parameter appended to each link in the campaign.
utmContentstringNonullThe utm_content marketing parameter appended to each link in the campaign.
utmMediumstringNonullThe utm_medium marketing parameter appended to each link in the campaign.
utmSourcestringNonullThe utm_source marketing parameter appended to each link in the campaign.

Attach the file as POST multipart/form-data file upload

Calling Send Email API

To use the send command please use POST to http://mail.themessaging.in/v2/email/send with the parameters listed below.


PARAMETERS:
* apikey=your api key,
* subject=email subject,
* from=from email address,
* to=List of email recipients (each email is treated separately, like a BCC). Separated by comma or semicolon. We suggest using the "msgTo" parameter.
* bodyHtml=html email body [optional],
* bodyText=text email body [optional],
* isTransactional - True, if email is transactional (non-bulk, non-marketing, non-commercial). Otherwise, false

API to send using C#.

		               
					using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace themessagingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection values = new NameValueCollection();
            values.Add("apikey", "00000000-0000-0000-0000-000000000000");
            values.Add("from", "youremail@yourdomain.com");
            values.Add("fromName", "Your Company Name");
            values.Add("to", "recipient1@gmail.com;recipient2@gmail.com");
            values.Add("subject", "Your Subject");
            values.Add("bodyText", "Text Body");
            values.Add("bodyHtml", "

Html Body

"); values.Add("isTransactional", true); string address = "http://mail.themessaging.in/v2/email/send"; string response = Send(address, values); Console.WriteLine(response); } static string Send(string address, NameValueCollection values) { using (WebClient client = new WebClient()) { try { byte[] apiResponse = client.UploadValues(address, values); return Encoding.UTF8.GetString(apiResponse); } catch (Exception ex) { return "Exception caught: " + ex.Message + "\n" + ex.StackTrace; } } } } }

API to send Using Java.

		               
					import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class themessagingClient {
 
 public static String Send(String userName, String apiKey, String from, String fromName, String subject, String body, String to, String isTransactional) {
 
 try {
 
 String encoding = "UTF-8";
 
 String data = "apikey=" + URLEncoder.encode(apiKey, encoding);
 data += "&from=" + URLEncoder.encode(from, encoding);
 data += "&fromName=" + URLEncoder.encode(fromName, encoding);
 data += "&subject=" + URLEncoder.encode(subject, encoding);
 data += "&bodyHtml=" + URLEncoder.encode(body, encoding);
 data += "&to=" + URLEncoder.encode(to, encoding);
 data += "&isTransactional=" + URLEncoder.encode(isTransactional, encoding);
 
 URL url = new URL("http://mail.themessaging.in/v2/email/send");
 URLConnection conn = url.openConnection();
 conn.setDoOutput(true);
 OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
 wr.write(data);
 wr.flush();
 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
 String result = rd.readLine();
 wr.close();
 rd.close();

 return result;
 }
 
 catch(Exception e) {
 
 e.printStackTrace();
 }
 }

}
						
					

API to send using PHP.

		               
						 'youremail@yourdomain.com',
		'fromName' => 'Your Company Name',
		'apikey' => '00000000-0000-0000-0000-000000000000',
		'subject' => 'Your Subject',
		'to' => 'recipient1@gmail.com;recipient2@gmail.com',
		'bodyHtml' => '

Html Body

', 'bodyText' => 'Text Body', 'isTransactional' => false); $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $post, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_SSL_VERIFYPEER => false )); $result=curl_exec ($ch); curl_close ($ch); echo $result; } catch(Exception $ex){ echo $ex->getMessage(); } ?>

API to send using Python.

		               
				import requests
import json
from enum import Enum
class ApiClient:
	apiUri = 'http://mail.themessaging.in/v2'
	apiKey = '00000000-0000-0000-0000-0000000000000'

	def Request(method, url, data):
		data['apikey'] = ApiClient.apiKey
		if method == 'POST':
			result = requests.post(ApiClient.apiUri + url, params = data)
		elif method == 'PUT':
			result = requests.put(ApiClient.apiUri + url, params = data)
		elif method == 'GET':
			attach = ''
			for key in data:
				attach = attach + key + '=' + data[key] + '&' 
			url = url + '?' + attach[:-1]
			result = requests.get(ApiClient.apiUri + url)	
			
		jsonMy = result.json()
		
		if jsonMy['success'] is False:
			return jsonMy['error']
			
		return jsonMy['data']

def Send(subject, EEfrom, fromName, to, bodyHtml, bodyText, isTransactional):
	return ApiClient.Request('POST', '/email/send', {
		'subject': subject,
		'from': EEfrom,
		'fromName': fromName,
		'to': to,
		'bodyHtml': bodyHtml,
		'bodyText': bodyText,
		'isTransactional': isTransactional})
				
print(Send("Your Subject", "youremail@yourdomain.com", "Your Company Name", "recipient1@gmail.com;recipient2@gmail.com", "

Html Body

", "Text Body", True))

Add Contact API

		               
					http://mail.themessaging.in/v2/contact/add?publicAccountID=EB3EBB7A-C20D-4D39-8F2F-5E6842F58E6F&email=mail@example.com&publicListID=public-id-of-your-list&listName=My List 1&firstName=FIRSTNAME&lastName=LASTNAME&source=&returnUrl=http://yourdomain.com&sourceUrl=http://source.url.com&activationReturnUrl=http://yourwebsite.com/thankyou&activationTemplate=&sendActivation=false&consentDate=1/1/2015 0:00:00 AM&consentIP=192.168.0.1&field_firstname=english¬ifyEmail=john@test.com&alreadyActiveUrl=&consentTracking=
						
					

Quick Add Contact API

		               
http://mail.themessaging.com/v2/contact/quickadd?apikey=94DAF66E-4DF6-4E8E-AF96-D094A8D21DF3&emails=mail@contact.com,mail1@contact.com,mail2@contact.com&firstName=FIRSTNAME&lastName=LASTNAME&publicListID=public-id-of-your-list&listName=My List 1&status=Bounced¬es=Contact is extremely important!&consentDate=1/1/2015 0:00:00 AM&consentIP=192.168.0.1&field_firstname=english¬ifyEmail=john@test.com&consentTracking=						
					

Send Email with Attachments

Sending with attachments is not that much different from Mail Merge. You need to provide your attachments as the Multipart/Form-Data POST field in your Send request, so the specific request's parameter for attachments does not exist. There is no limit on how many attachments you can send with the email.

Note: There is currently a limit of 10 MB/overall email size.

API to send using C#.

		               
						using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;

namespace themessagingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection values = new NameValueCollection();
            values.Add("apikey", "00000000-0000-0000-0000-000000000000");
            values.Add("from", "youremail@yourdomain.com");
            values.Add("fromName", "Your Company Name");
            values.Add("subject", "Your Subject");
            values.Add("bodyText", "Text Body");
            values.Add("to", "recipient1@gmail.com;recipient2@gmail.com");
            values.Add("bodyHtml", "<h1>Html Body</h1>");
            
            var filepath = "C:\\example\\helloWorld.txt";
            var file = File.OpenRead(filepath);

            var filesStream = new Stream[] { file };
            var filenames = new string[] { "filenameForInbox.txt" };
            var URL = "http://mail.themessaging.in/v2/email/send";

            string result = Upload(URL, values, filesStream, filenames);

            Console.WriteLine(result);
        }

        public static string Upload(string actionUrl, NameValueCollection values, Stream[] paramFileStream = null, string[] filenames = null)
        {
            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent())
            {
                foreach (string key in values)
                {
                    HttpContent stringContent = new StringContent(values[key]);
                    formData.Add(stringContent, key);
                }

                for (int i = 0; i < paramFileStream.Length; i++)
                {
                    HttpContent fileStreamContent = new StreamContent(paramFileStream[i]);
                    formData.Add(fileStreamContent, "file" + i, filenames[i]);
                }

                var response = client.PostAsync(actionUrl, formData).Result;
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(response.Content.ReadAsStringAsync().Result);
                }

                return response.Content.ReadAsStringAsync().Result;
            }
        }

    }
}
						
					

API to send usingPHP.

		               
				 'youremail@yourdomain.com',
                      'fromName' => 'Your Company Name',
                      'apikey' => '00000000-0000-0000-0000-000000000000',
                      'subject' => 'Your Subject',
                      'bodyHtml' => '<h1>Html Body</h1>',
                      'bodyText' => 'Text Body',
                      'to' => 'recipient1@gmail.com;recipient2@gmail.com',
                      'isTransactional' => false,
                      'file_1' => new CurlFile($file_name_with_full_path, $filetype, $filename));
        
        $ch = curl_init();
            
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $post,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_SSL_VERIFYPEER => false
        ));
        
        $result=curl_exec ($ch);
        curl_close ($ch);
        
        echo $result;    
}
catch(Exception $ex){
    echo $ex->getMessage();
}
?>
						
					

API to send using Java.

		               
					--------------ElasticClient.java--------
package com.themessaging.app;

import java.io.IOException;
import java.util.HashMap;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ElasticClient {
    public static void main(String[] args) {
        API client = new API();
        ArrayListfiles = new ArrayList<>();
        String filename = "helloWorld.txt";
        
        Path path = Paths.get("C:\\example\\" + filename);
        byte[] data = null;
        try {
            data = Files.readAllBytes(path);
        } catch (IOException ex) {
            Logger.getLogger(ElasticClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        FileData contactsFile = new FileData();
        contactsFile.contentType = "text/plain"; // Change correspondingly to the file type
        contactsFile.fileName = filename;
        contactsFile.content = data;
        files.add(contactsFile);
        
        HashMap values = new HashMap<>();
        values.put("apikey", "00000000-0000-0000-0000-000000000000");
        values.put("from", "youremail@yourdomain.com");
        values.put("fromName", "Your Company Name");
        values.put("subject", "Your Subject");
        values.put("to", "recipient1@gmail.com;recipient2@gmail.com");
        values.put("bodyText", "Text Body");
        values.put("bodyHtml", "<h1>Html Body</h1>");
        
        try {
            String result = client.httpPostFile("/email/send", files, values);
            System.out.println(result);
        } catch (Exception ex) {
            Logger.getLogger(ElasticClient.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }              
}


-------------- API.java ----------------
package com.themessaging.app;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

public class API {
    
    public static String API_KEY = "";
    protected static String API_URI = "http://mail.themessaging.in/v2";

    protected String httpPostFile(String targetURL, Iterable fileData, Map values) throws Exception {
        if (targetURL == null) throw new IllegalArgumentException("targetURL");
        if (values == null) throw new IllegalArgumentException("values");
        if (fileData == null) throw new IllegalArgumentException("fileData");

        HttpURLConnection connection = null;
        URL url = null;
        String urlParameters = null;
        String urlParametersLength = null;

        try {
            url = new URL(API_URI + targetURL);
            urlParameters = loadUrlParameters(values);
            urlParametersLength = Integer.toString(urlParameters.getBytes().length);
            String boundary = String.valueOf(System.currentTimeMillis());
            byte[] boundarybytes = ("\r\n--" + boundary + "\r\n").getBytes(Charset.forName("ASCII"));

            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Length", "" + urlParametersLength);
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());

        String formdataTemplate = "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s";
        for (String key : values.keySet())
        {
            wr.write(boundarybytes, 0, boundarybytes.length);
            String formitem = String.format(formdataTemplate, key, values.get(key));
            byte[] formitembytes = formitem.getBytes(Charset.forName("UTF8"));
            wr.write(formitembytes, 0, formitembytes.length);
        }

        if(fileData != null){
            for(FileData file : fileData){
                wr.write(boundarybytes, 0, boundarybytes.length);
                String headerTemplate = "Content-Disposition: form-data; name=\"filefoobarname\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n";
                String header = String.format(headerTemplate, file.fileName, file.contentType);
                byte[] headerbytes = header.getBytes(Charset.forName("UTF8"));
                wr.write(headerbytes, 0, headerbytes.length);
                wr.write(file.content, 0, file.content.length);
            }
        }

        byte[] trailer = ("\r\n--" + boundary + "--\r\n").getBytes(Charset.forName("ASCII"));
        wr.write(trailer, 0, trailer.length);
        wr.flush ();
        wr.close ();

        //Get Response    
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder(); 
        while((line = rd.readLine()) != null) {
          response.append(line);
          response.append('\r');
        }
        rd.close();

        return response.toString();

        } catch (IOException e) { 
            e.printStackTrace();
            return null;

        } finally {
            if(connection != null) {
                connection.disconnect(); 
            }
        }
    }    
        
    private String loadUrlParameters(Map values) {
        StringBuilder sb = new StringBuilder();

        values.keySet().forEach((key) -> {
            if (sb.length() > 0) {
                sb.append("&");
            }
            String value = values.get(key);
            try {
                sb.append((key != null ? URLEncoder.encode(key, "UTF-8") : ""));
                sb.append("=");
                sb.append(value != null ? URLEncoder.encode(value, "UTF-8") : "");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("This method is not supported", e);
            }
        });
        
        return sb.toString();
    }
}


---------------- FileData.java -----------------------
package com.themessaging.app;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileData {
    public byte[] content;
    
    public String contentType;

    public String fileName;
    
    public void ReadFrom(String pathWithFileName) throws Exception
    {
        Path path = Paths.get(pathWithFileName);
        content = Files.readAllBytes(path);
        fileName = path.getFileName().toString(); 
        contentType = null;
    }

    public static FileData CreateFromFile(String pathWithFileName) throws Exception
    {
        FileData fileData = new FileData();
        fileData.ReadFrom(pathWithFileName);
        return fileData;
    }
}
						
					

API to send using Python.

		               
					import requests
import json
from enum import Enum

class ApiClient:
    apiUri = 'http://mail.themessaging.in/v2'
    apiKey = '00000000-0000-0000-0000-000000000000'

    def Request(method, url, data, attachs=None):
        data['apikey'] = ApiClient.apiKey
        if method == 'POST':
            result = requests.post(ApiClient.apiUri + url, params = data, files = attachs)
        elif method == 'PUT':
            result = requests.put(ApiClient.apiUri + url, params = data)
        elif method == 'GET':
            attach = ''
            for key in data:
                attach = attach + key + '=' + data[key] + '&' 
            url = url + '?' + attach[:-1]
            result = requests.get(ApiClient.apiUri + url)    
            
        jsonMy = result.json()
        
        if jsonMy['success'] is False:
            return jsonMy['error']
            
        return jsonMy['data']

def Send(subject, EEfrom, fromName, to, bodyHtml, bodyText, isTransactional, contactsSourceFilename, attachmentFiles = []):
    attachments = []
    for name in attachmentFiles:
        attachments.append(('attachments'.name, open(name, 'rb')))
        
    return ApiClient.Request('POST', '/email/send', {
                'subject': subject,
                'from': EEfrom,
                'fromName': fromName,
                'to': to,
                'bodyHtml': bodyHtml,
                'bodyText': bodyText,
                'isTransactional': isTransactional}, attachments)
    
attachments = []
attachments.append('C:/example/helloWorld.txt')
print(Send("Your Subject", "youremail@yourdomain.com", "Your Company Name", "recipient1@gmail.com;recipient2@gmail.com", "<h1>Html Body</h1>", "Text Body", True, attachments))
						
					

Learn how to send customized emails to multiple recipients with Mail Merge function.

Using this technique you can define an email template which contains special fields such as {firstname}, {lastname} or many others and send personalized emails in a very efficient way to your clients.

For example: Dear {firstname} {lastname},

2. If you're sending via API using the "Email_Send" method, you can select the list or segment with a "lists" or "segments" call. You can select multiple by separating them with a comma or semicolon. If you want to send to "All Contacts", use "0".

This is our monthly newsletter. We hope you have been enjoying our service. You can access your account at {link}.

If you would like to allow custom headers, please make sure this has been activated on your advanced options screen.

Create a CSV file

Create a CSV file like the following:

"ToEmail","FirstName","LastName"

"email1@email.com","Joe","Plumber"

"email2@email.com", "Jackie","Smith"

The first column of the data must be ToEmail and will be used as the recipients of the merged email. The other columns represent the data fields that you can use in your email. You can have as many columns as you need. If you have the header FirstName you can include that in your email template with {FirstName} and all references to that field will be replaced before sending.

Send Email

To use the send POST command to http://mail.themessaging.in/v2/email/send with the following form values:
username=your account email address,
api_key=your API key,
from=from email address,
from_name=display name for from email address,
subject=email subject,
body_html=html email body [optional],
body_text=text email body [optional],
mergesourcefilename=your CSV file name sent with this call as an attachment,
charset=text value of encoding for example: iso-8859-1, windows-1251, utf-8, us-ascii, windows-1250 and more…,
encoding for None, 1 for Raw7Bit, 2 for Raw8Bit, 3 for QuotedPrintable, 4 for Base64 (Default), 5 for Uue (note that you can also provide the text version such as "Raw7Bit" for value 1).
If sent correctly you will receive a response like:
{"success":true,"data":{"transactionid":"d6126dc1-d012-4d4c-b75b-43ak8dd7df9c","messageid":"7jAW8_jz5Iaw7DjsPaaH9A2"}}'
This contains the transaction ID of your send job. You can use this transaction ID to check on the statistics of the given job using the Get Status API.
Your email will be sent to each email address in the CSV file and the data will be merged with the CSV data.
Note: There is a limit of 100000 emails / uploaded CSV file for larger jobs please split into separate calls.

Mail Merge with single recipient

You can also use the merge fields when sending to a single recipient. You can, of course, create a CSV file with one recipient and follow our instructions mentioned above, or you could create the merge fields' values on the go:
Simply use a merge field in your bodyHtml or bodyText ("Hello, {firstname}" etc.) and provide its value at the same request by following the given convention:
merge_X = Y
For the given firstname, it would be:
merge_firstname=John
Implement how many fields you need and provide them with the Send request just as you would provide a subject or body HTML, and you are ready to go!

API to send using C#.

		               
					using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;

namespace themessagingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection values = new NameValueCollection();
            values.Add("apikey", "00000000-0000-0000-0000-000000000000");
            values.Add("from", "youremail@yourdomain.com");
            values.Add("fromName", "Your Company Name");
            values.Add("subject", "Your Subject");
            values.Add("bodyText", "Hello, {firstname}");
            values.Add("bodyHtml", "

Hello, {firstname}

"); values.Add("mergesourcefilename", "mycontacts.csv"); // Same as the name of the file in the 'filenames' array var filepath = "C:\\example\\contacts.csv"; var file = File.OpenRead(filepath); // multiple files can be sent using this method var filesStream = new Stream[] { file }; var filenames = new string[] { "mycontacts.csv" }; var URL = "http://mail.themessaging.in/v2/email/send"; string result = Upload(URL, values, filesStream, filenames); Console.WriteLine(result); } public static string Upload(string actionUrl, NameValueCollection values, Stream[] paramFileStream = null, string[] filenames = null) { using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { foreach (string key in values) { HttpContent stringContent = new StringContent(values[key]); formData.Add(stringContent, key); } for (int i = 0; i < paramFileStream.Length; i++) { HttpContent fileStreamContent = new StreamContent(paramFileStream[i]); formData.Add(fileStreamContent, "file" + i, filenames[i]); } var response = client.PostAsync(actionUrl, formData).Result; if (!response.IsSuccessStatusCode) { throw new Exception(response.Content.ReadAsStringAsync().Result); } return response.Content.ReadAsStringAsync().Result; } } } }

API to send using PHP.

		               
						 'youremail@yourdomain.com',
		'fromName' => 'Your Company Name',
		'apikey' => '00000000-0000-0000-0000-000000000000',
		'subject' => 'Your Subject',
		'bodyHtml' => '

Hello, {firstname}

', 'bodyText' => 'Hello, {firstname}', 'isTransactional' => false, 'file_contacts' => new CurlFile($file_name_with_full_path, 'text/csv', $filename), 'mergesourcefilename' => $filename); $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $post, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_SSL_VERIFYPEER => false )); $result=curl_exec ($ch); if ($result === FALSE) { echo curl_error($ch); } else { echo $result; } curl_close ($ch); } catch(Exception $ex){ echo $ex->getMessage(); } ?>

API to send using JAVA.

		               
	--------------ElasticClient.java--------
package com.themessaging.app;

import java.io.IOException;
import java.util.HashMap;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ElasticClient {
    public static void main(String[] args) {
        API client = new API();
        ArrayListfiles = new ArrayList<>();
        String filename = "Contacts.csv";
        
        Path path = Paths.get("C:\\example\\" + filename);
        byte[] data = null;
        try {
            data = Files.readAllBytes(path);
        } catch (IOException ex) {
            Logger.getLogger(ElasticClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        FileData contactsFile = new FileData();
        contactsFile.contentType = "text/csv";
        contactsFile.fileName = filename;
        contactsFile.content = data;
        files.add(contactsFile);
        
        HashMap values = new HashMap<>();
        values.put("apikey", "00000000-0000-0000-0000-000000000000");
        values.put("from", "youremail@yourdomain.com");
        values.put("fromName", "Your Company Name");
        values.put("subject", "Your Subject");
        values.put("bodyText", "Hello, {firstname}");
        values.put("bodyHtml", "

Hello, {firstname}

"); values.put("mergesourcefilename", filename); try { String result = client.httpPostFile("/email/send", files, values); System.out.println(result); } catch (Exception ex) { Logger.getLogger(ElasticClient.class.getName()).log(Level.SEVERE, null, ex); } } } -------------- API.java ---------------- package com.themessaging.app; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Map; public class API { public static String API_KEY = ""; protected static String API_URI = "http://mail.themessaging.in/v2"; protected String httpPostFile(String targetURL, Iterable fileData, Map values) throws Exception { if (targetURL == null) throw new IllegalArgumentException("targetURL"); if (values == null) throw new IllegalArgumentException("values"); if (fileData == null) throw new IllegalArgumentException("fileData"); HttpURLConnection connection = null; URL url = null; String urlParameters = null; String urlParametersLength = null; try { url = new URL(API_URI + targetURL); urlParameters = loadUrlParameters(values); urlParametersLength = Integer.toString(urlParameters.getBytes().length); String boundary = String.valueOf(System.currentTimeMillis()); byte[] boundarybytes = ("\r\n--" + boundary + "\r\n").getBytes(Charset.forName("ASCII")); connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Length", "" + urlParametersLength); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream ()); String formdataTemplate = "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s"; for (String key : values.keySet()) { wr.write(boundarybytes, 0, boundarybytes.length); String formitem = String.format(formdataTemplate, key, values.get(key)); byte[] formitembytes = formitem.getBytes(Charset.forName("UTF8")); wr.write(formitembytes, 0, formitembytes.length); } if(fileData != null){ for(FileData file : fileData){ wr.write(boundarybytes, 0, boundarybytes.length); String headerTemplate = "Content-Disposition: form-data; name=\"filefoobarname\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n"; String header = String.format(headerTemplate, file.fileName, file.contentType); byte[] headerbytes = header.getBytes(Charset.forName("UTF8")); wr.write(headerbytes, 0, headerbytes.length); wr.write(file.content, 0, file.content.length); } } byte[] trailer = ("\r\n--" + boundary + "--\r\n").getBytes(Charset.forName("ASCII")); wr.write(trailer, 0, trailer.length); wr.flush (); wr.close (); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (IOException e) { e.printStackTrace(); return null; } finally { if(connection != null) { connection.disconnect(); } } } private String loadUrlParameters(Map values) { StringBuilder sb = new StringBuilder(); values.keySet().forEach((key) -> { if (sb.length() > 0) { sb.append("&"); } String value = values.get(key); try { sb.append((key != null ? URLEncoder.encode(key, "UTF-8") : "")); sb.append("="); sb.append(value != null ? URLEncoder.encode(value, "UTF-8") : ""); } catch (UnsupportedEncodingException e) { throw new RuntimeException("This method is not supported", e); } }); return sb.toString(); } } ---------------- FileData.java ----------------------- package com.themessaging.app; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileData { public byte[] content; public String contentType; public String fileName; public void ReadFrom(String pathWithFileName) throws Exception { Path path = Paths.get(pathWithFileName); content = Files.readAllBytes(path); fileName = path.getFileName().toString(); contentType = null; } public static FileData CreateFromFile(String pathWithFileName) throws Exception { FileData fileData = new FileData(); fileData.ReadFrom(pathWithFileName); return fileData; } }

API to send using Python.

		               
					import requests
import json
from enum import Enum

class ApiClient:
	apiUri = 'http://mail.themessaging.in/v2'
	apiKey = '00000000-0000-0000-0000-000000000000'

	def Request(method, url, data, attachs=None):
		data['apikey'] = ApiClient.apiKey
		if method == 'POST':
			result = requests.post(ApiClient.apiUri + url, params = data, files = attachs)
		elif method == 'PUT':
			result = requests.put(ApiClient.apiUri + url, params = data)
		elif method == 'GET':
			attach = ''
			for key in data:
				attach = attach + key + '=' + data[key] + '&' 
			url = url + '?' + attach[:-1]
			result = requests.get(ApiClient.apiUri + url)	
			
		jsonMy = result.json()
		
		if jsonMy['success'] is False:
			return jsonMy['error']
			
		return jsonMy['data']

def Send(subject, EEfrom, fromName, bodyHtml, bodyText, isTransactional, contactsSourceFilename, attachmentFiles = []):
	attachments = []
	for name in attachmentFiles:
		attachments.append(('attachments'.name, open(name, 'rb')))
		
	return ApiClient.Request('POST', '/email/send', {
		'subject': subject,
		'from': EEfrom,
		'fromName': fromName,
		'bodyHtml': bodyHtml,
		'bodyText': bodyText,
		'mergesourcefilename': contactsSourceFilename,
		'isTransactional': isTransactional}, attachments)
    
attachments = []
attachments.append('C:/example/Contacts.csv')
print(Send("Your Subject", "youremail@yourdomain.com", "Your Company Name", "

Hello, {firstname}

", "Hello, {firstname}", True, "Contacts.csv", attachments))

Custom Headers

Learn how to add Custom Headers in your emails.

Custom headers are a great solution if you want to send debug info or any data you want along with the given email.
If you would like to add custom headers to your email you can do so by defining request parameters prefixed by headers_, like 'headers_customheader1', and by setting its value following a convention: 'customheader1: sometext'.
Note: space is required after the colon and before the custom header value!
For example: headers_comments=comments: This is a test"
Note: In order to pass Custom Headers in your emails please enable "Allow Custom Headers" option on your Settings screen.

Custom PostBack header

You can also use this feature to send a postback header, which is a header that is returned in our system's notifications sent to you regarding your emails.
Example 1 - basic Postback header :
postback=This is a test
will result in a postback header
X-PostBack=This is a test

API to send using C#.

		               
					using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace themessagingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection values = new NameValueCollection();
            values.Add("apikey", "00000000-0000-0000-0000-000000000000");
            values.Add("from", "youremail@yourdomain.com");
            values.Add("fromName", "Your Company Name");
            values.Add("to", "recipient1@gmail.com;recipient2@gmail.com");
            values.Add("subject", "Your Subject");
            values.Add("bodyText", "Text Body");
            values.Add("bodyHtml", "<h1>Html Body</h1>");
            values.Add("isTransactional", true);
            values.Add("headers_comments", "Comments: Let John know if you can see the emojis");
            values.Add("postback", "Just want this back if the email fails");

            string address = "http://mail.themessaging.in/v2/email/send";

            string response = Send(address, values);

            Console.WriteLine(response);
        }

        static string Send(string address, NameValueCollection values)
        {
            using (WebClient client = new WebClient())
            {
                try
                {
                    byte[] apiResponse = client.UploadValues(address, values);
                    return Encoding.UTF8.GetString(apiResponse);

                }
                catch (Exception ex)
                {
                    return "Exception caught: " + ex.Message + "\n" + ex.StackTrace;
                }
            }
        }

    }
}
						
					

API to send using java/strong>.

		               
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class themessagingClient {
 
 public static String Send(String userName, String apiKey, String from, String fromName, String subject, String body, String to, String isTransactional) {
 
 try {
 
 String encoding = "UTF-8";
 
 String data = "apikey=" + URLEncoder.encode(apiKey, encoding);
 data += "&from=" + URLEncoder.encode(from, encoding);
 data += "&fromName=" + URLEncoder.encode(fromName, encoding);
 data += "&subject=" + URLEncoder.encode(subject, encoding);
 data += "&bodyHtml=" + URLEncoder.encode(body, encoding);
 data += "&to=" + URLEncoder.encode(to, encoding);
 data += "&isTransactional=" + URLEncoder.encode(isTransactional, encoding);
 
 URL url = new URL("http://mail.themessaging.in/v2/email/send");
 URLConnection conn = url.openConnection();
 conn.setDoOutput(true);
 OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
 wr.write(data);
 wr.flush();
 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
 String result = rd.readLine();
 wr.close();
 rd.close();

 return result;
 }
 
 catch(Exception e) {
 
 e.printStackTrace();
 }
 }

}
						
					

API to send using PHP without CURL.

		               
				 'youremail@yourdomain.com',
                      'fromName' => 'Your Company Name',
                      'apikey' => '00000000-0000-0000-0000-000000000000',
                      'subject' => 'Your Subject',
                      'to' => 'recipient1@gmail.com;recipient2@gmail.com',
                      'bodyHtml' => '<h1>Html Body</h1>',
                      'bodyText' => 'Text Body',
                      'isTransactional' => false,
                      'headers_comments' => 'Comments: Let John know if you can see the emojis',
                      'postback' => 'Just want this back if the email fails');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

?>