by Anna Wybieralska Dec 2, 2016

Send an email to a single recipient or group of recipients.

This is a deprecated API Call. For Updated API Documentation, please click here.

The following documentation is for our API v1 which is supported, but no longer developed.

For sending, we recommend using API v2

The send command is used to send an email to a single recipient or multiple recipients.

To use the send command POST to https://api.elasticemail.com/mailer/send with the parameters listed below.

Parameters:

username=your account email address,

api_key=your api key,

from=from email address,

from_name=display name for from email address,

to=semi colon separated list of email recipients (each email is treated separately, like a BCC),

subject=email subject,

body_html=html email body [optional],

body_text=text email body [optional],

reply_to=email address to reply to [optional],

reply_to_name=display name of the reply to address [optional],

channel=an id field (max 60 chars) that can be used for reporting [optional - will default to HTTP API or SMTP API],

charset=text value of encoding for example: iso-8859-1, windows-1251, utf-8, us-ascii, windows-1250 and more…,

encodingtype=0 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.

Optional Templates, Segments, and Lists

template=the name of an email template you have created in your account. If you send a template [optional],

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. [optional],

lists=the name of a contact list you would like to send to. Separate multiple contacts lists by commas. [optional],

segments=the name of a segment you would like to send to. Separate multiple segments by commas,

sender=email address of the sender [optional],

sender_name=display name sender [optional],

time_offset_minutes=number of minutes in the future this email should be sent [optional].

Optional Custom Headers

If you would like to add custom headers to your email you can do so by defining parameter's header1, header2, header3, etc and providing it a custom header name and header value.

Note: space is required after the colon before the custom header value.

header1=customheader1: header-value1,

header2=customheader2: header-value2

header3=customheader3: header-value3,

etc.

Attachments

If you would like to prepare and send an attachment with your email, please refer to this attachment upload help.

Note: When you have more than one recipient in the "to" field each recipient will receive their own individually delivered copy of the email. Recipients will not see each other's email addresses.

Response

Optional sender header

If you are sending on behalf of many clients with different from addresses use:

Optional scheduling

If you would like to schedule your email to be delivered in the future (drip campaigns etc):

If sent correctly you will receive a response like:

f74b9f96-f89a-4cfe-813f-5f86df1cb37f

This is the transaction ID of your send job. You can use this transaction ID to check on the status of the given job using the Get Status API.

Code Examples

Check out code examples for quick integration.

PHP

function sendElasticEmail($to, $subject, $body_text, $body_html, $from, $fromName)
{
 $res = "";

 $data = "username=".urlencode("YOUR ACCOUNT EMAIL ADDRESS");
 $data .= "&api_key=".urlencode("YOUR API KEY");
 $data .= "&from=".urlencode($from);
 $data .= "&from_name=".urlencode($fromName);
 $data .= "&to=".urlencode($to);
 $data .= "&subject=".urlencode($subject);
 if($body_html)
 $data .= "&body_html=".urlencode($body_html);
 if($body_text)
 $data .= "&body_text=".urlencode($body_text);

 $header = "POST /mailer/send HTTP/1.0\r\n";
 $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
 $header .= "Content-Length: " . strlen($data) . "\r\n\r\n";
 $fp = fsockopen('ssl://api.elasticemail.com', 443, $errno, $errstr, 30);


PHP-Zend

<?php

/**
 * This class implements a Zend_Mail_Transport to dispatch emails
 * via Elastic Email (www.elasticemail.com). This class is provided
 * AS IS, without any warranty.
 *
 * @author Marco Pracucci <marco.pracucci@spreaker.com>
 * @author Rocco Zanni <rocco.zanni@spreaker.com>
 * @copyright Spreaker
 * @link www.spreaker.com
 */
class spEmailTransportElasticEmail extends Zend_Mail_Transport_Abstract
{
 /**
 * Api send uri
 * @var string
 */
 private $_api_uri = 'https://api.elasticemail.com/mailer/send';



PHP CURL

<?php
/**
 * Send Elastic Email using cURL (libcurl) in PHP
 *
 * Configuration:
 * 1. View certificate used at https://api.elasticemail.com/
 * 2. Save X.509 Certificate-Chained (PEM) to some location on your server
 * 3. Set path accordingly to certificate location
 * 4. Set username and password
 * 5. cURLElasticEmail
*/
function cURLElasticEmail($to, $subject, $body_text, $body_html, $from, $from_name) {
 
 // Initialize cURL
 $ch = curl_init();
 
 // Set cURL options
 curl_setopt($ch, CURLOPT_URL, 'https://api.elasticemail.com/mailer/send');
 curl_setopt($ch, CURLOPT_POST, 1);




PowerShell in PHP

/*

Send Elastic Email using Windows PowerShell in PHP 
%credits: http://www.coreindex.com/ - a B2B social network

*/

function sendShellElasticEmail($to, $subject, $body_text, $body_html, $from, $fromName){

 $data = "username=".urlencode("YOUR ACCOUNT EMAIL ADDRESS"); 
 $data .= "&api_key=".urlencode("YOUR API KEY"); 
 $data .= "&from=".urlencode($from); 
 $data .= "&from_name=".urlencode($fromName); 
 $data .= "&to=".urlencode($to); 
 $data .= "&subject=".urlencode($subject); 
 if($body_html) $data .= "&body_html=".urlencode($body_html); 
 if($body_text) $data .= "&body_text=".urlencode($body_text); 
 $header = "POST /mailer/send HTTP/1.0\r\n"; 
 $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
 $header .= "Content-Length: " . strlen($data) . "\r\n\r\n";

$b64string=base64_encode($header.$data);

$cmd="powershell.exe \" \$Socket=New-Object Net.Sockets.TcpClient; \$Socket.Connect('api.elasticemail.com','443'); if (\$Socket.Connected){ \$data = [System.Text.Encoding]::ASCII.GetBytes( [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String( '$b64string') ) ); \$Stream=\$Socket.GetStream(); \$sslStream = New-Object System.Net.Security.SslStream(\$Stream,\$false,({\$True} -as [Net.Security.RemoteCertificateValidationCallback])); \$sslStream.AuthenticateAsClient('localhost'); \$writer = new-object System.IO.StreamWriter(\$sslStream); \$writer.Write(\$data, 0, \$data.Length); \$writer.flush(); \$Socket.Close();}else{write-host 'ERROR. Could not open connection';} \" ";

shell_exec($cmd); 
}

echo sendShellElasticEmail("test@test.com", "My Subject", "My Text", "My HTML", "youremail@yourdomain.com", "Your Name");




C#

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

namespace BasicElasticEmailSend
{
 class Program
 {
 public static string USERNAME = "youremail@yourdomain.com";
 public static string API_KEY = "3d649332-2295-4a03-b03c-efc8ce671192";

 static void Main(string[] args)
 {

 string from = "youremail@yourdomain.com";
 string fromName = "Your Company Name";
 string to = "recipient1@gmail.com;recipient2@gmail.com;";
 string subject = "Your Subject";
 string bodyHtml = "<h1>Html Body</h1>"; 
 string bodyText = "Text Body";

 string result = SendEmail(to, subject, bodyText, bodyHtml, from, fromName);
 Console.WriteLine(result);
 }

 public static string SendEmail(string to, string subject, string bodyText, string bodyHtml, string from, string fromName)
 {

 WebClient client = new WebClient();
 NameValueCollection values = new NameValueCollection();
 values.Add("username", USERNAME);
 values.Add("api_key", API_KEY);
 values.Add("from", from);
 values.Add("from_name", fromName);
 values.Add("subject", subject);
 if (bodyHtml != null)
 values.Add("body_html", bodyHtml);
 if (bodyText != null)
 values.Add("body_text", bodyText);
 values.Add("to", to);

 byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values);
 return Encoding.UTF8.GetString(response);
 }
 }
}



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 ElasticEmail {
 
 public static String SendElasticEmail(String userName, String apiKey, String from, String fromName, String subject, String body, String to) {
 
 try {
 
 //Construct the data
 String data = "userName=" + URLEncoder.encode(userName, "UTF-8");
 data += "&api_key=" + URLEncoder.encode(apiKey, "UTF-8");
 data += "&from=" + URLEncoder.encode(from, "UTF-8");
 data += "&from_name=" + URLEncoder.encode(fromName, "UTF-8");
 data += "&subject=" + URLEncoder.encode(subject, "UTF-8");
 data += "&body_html=" + URLEncoder.encode(body, "UTF-8");
 data += "&to=" + URLEncoder.encode(to, "UTF-8");
 
 //Send data
 URL url = new URL("https://api.elasticemail.com/mailer/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();
 }
 }

}




Python

#!/usr/bin/env python 

# Import necessary modules 
import urllib 
import httplib 
import re 

# Globals 
USERNAME = '<Elastic Email Account Username>' 
API_KEY = '<Elastic Email Account API Key>' 
API_SERVER = 'api.elasticemail.com' 
API_URI = '/mailer/send' 
SUCCESS_MATCH_PATTERN = '^[0-9|a-f]{8}-[0-9|a-f]{4}-[0-9|a-f]{4}-[0-9|a-f]{4}-[0-9|a-f]{12}$' 
ERROR_MATCH_PATTERN = '^Error:' 

# Function to send e-mail 
def send_email(to_addr, subject, body_text, body_html, from_addr, from_name, reply_to_email=None, reply_to_name=None, channel=None): 

 # Build message structure 
 msg_info = {} 
 msg_info['username'] = USERNAME 
 msg_info['api_key'] = API_KEY 
 msg_info['from'] = from_addr 
 msg_info['from_name'] = from_name 
 msg_info['to'] = to_addr 
 msg_info['subject'] = subject 
 msg_info['body_text'] = body_text 
 msg_info['body_html'] = body_html 
 msg_info['reply_to'] = reply_to_email 
 msg_info['reply_to_name'] = reply_to_name 
 msg_info['channel'] = channel 

 # Prepare the API call 
 params = urllib.urlencode(msg_info) 
 headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'} 

 try: 
 # Connect to the API and send the message 
 conn = httplib.HTTPSConnection(API_SERVER) 
 conn.request('POST', API_URI, params, headers) 
 response = conn.getresponse() 

 # Read the response from the mail server, close the connection, and return the result 
 ret = response.read() 
 conn.close() 
 except Exception, e: 
 ret = str(e) 

 return ret 

# Main function 
if __name__ == '__main__': 

 # Call function to send e-mail 
 result = send_email('test@test.com', 'My Subject', 'Body text', '<b>Body</b> <i>HTML</i>', 'youremail@yourdomain.com', 'Your Name', 'donotreply@donotreply.com', 'Do not reply', 'Channel Name') 

 # Check return value 
 if re.search(SUCCESS_MATCH_PATTERN, result): 
 print 'Success: ' + result 
 elif re.search(ERROR_MATCH_PATTERN, result): 
 print result 
 else: 
 print 'Unrecognized return: ' + result 



Perl

#!/usr/bin/perl -w

use strict;

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;

my $USERNAME = 'YOUR USERNAME';
my $API_KEY = 'YOUR API KEY';
my $API_SERVER = 'api.elasticemail.com';
my $API_URI = '/mailer/send';
my $API_URL = 'http://'.$API_SERVER.$API_URI;

sub sendElasticEmail
{
 my ($from,$to,$subject,$body_html,$body_txt) = @_;

 my $ua = LWP::UserAgent->new;
 my $req = POST $API_URL,
 [ 
 username => $USERNAME,
 api_key => $API_KEY,
 subject=>$subject,
 from=>$from,
 to=>$to,
 body_html=>$body_html,
 body_text=>$body_txt
 ];

 print $ua->request($req)->as_string;
}

sendElasticEmail('from@test.com','to@target.com','My subject','My HTML','My TXT');


ASP.NET

<%
Sub sendElasticEmail(to, subject, body_text, body_html, from, fromName)
{
 elastic_api = "https://api.elasticemail.com/mailer/send"
 elastic_api = elastic_api & "?username=" & "YOUR ACCOUNT EMAIL ADDRESS"
 elastic_api = elastic_api & "&api_key=" & "YOUR API KEY"
 elastic_api = elastic_api & "&to=" & Server.URLEncode(to)
 elastic_api = elastic_api & "&subject=" & Server.URLEncode(subject)
 elastic_api = elastic_api & "&body_html=" & Server.URLEncode(body_html)
 elastic_api = elastic_api & "&body_text=" & Server.URLEncode(body_text)
 elastic_api = elastic_api & "&from=" & Server.URLEncode(from)
 elastic_api = elastic_api & "&from_name=" & Server.URLEncode(fromName)
 
 Dim objXMLHTTP, res
 Set res = Server.CreateObject ("Microsoft.XMLHTTP")
 res.Open "GET", elastic_api, false
 res.Send
 
 if InStr(res, "Error")<> 0 then
 response.write "ERROR.<br>" & res
 else
 response.write "Success.<br>Transaction ID:" & res
 end if
 
}
sendElasticEmail "test@test.com", "My Subject", "My Text", "My HTML", "youremail@yourdomain.com", "Your Name"
%>



Force.com

//Force.com 
//Sample of using elastic email
//Emails sent with standard force.com calls count against daily mass email limit
public with sharing class ElasticEmail {
 
 private static final String API_KEY = '##-Set the key here-##';
 private static final String USER_NAME = '## Set your username here ####';
 
 //overload method to mask the need to send username and key but kept the original for flexibility
 public static String SendElasticEmail(String fromEmail, String fromName, 
 String subject, String body, String toEmail) {
 
 return ElasticEmail.SendElasticEmail(USER_NAME, API_KEY, fromEmail, fromName, 
 subject, body, toEmail);
 
 }
 
 //send the email
 public static String SendElasticEmail(String userName, String APIKey, String fromEmail, 
 String fromName, String subject, String body, String toEmail) {
 
 Http http = new Http();
 HttpRequest req = new HttpRequest();
 HTTPResponse res;
 req.setEndpoint('https://api.elasticemail.com/mailer/send');
 req.setMethod('POST'); 
 
 try { 
 //Construct the data
 String data = 'userName=' + userName;
 data += '&api_key=' + APIKey;
 data += '&from=' + fromEmail;
 data += '&from_name=' + fromName;
 data += '&subject=' + EncodingUtil.urlEncode(subject, 'UTF-8');
 data += '&body_text=' + EncodingUtil.urlEncode(body, 'UTF-8');
 data += '&to=' + toEmail;
 req.setBody(data);
 
 res = http.send(req);
 
 //Send data
 System.debug(res.getBody()); 

 return res.getBody();
 }
 
 catch(Exception e) {
 
 return null;
 }

 }
 
 //a simplified method to send an email to a user 
 public static String sendEmail(User u) {
 return ElasticEmail.SendElasticEmail('customer.service@mydomain.com', 'Customer Service', 
 'Subject', ElasticEmail.EmailBody(u), u.Email);
 }
 
 public static String EmailBody(User u) {
 String eBody = 'Dear ' + u.FirstName + ',\n\n';
 eBody += 'You are receiving this email with Elastic Email.\n\n'; 
 eBody += 'Sincerly,\n\n Customer Service';
 return eBody;
 }
 
 static testMethod void testElasticEmail() {
 User u = [Select FirstName, Id from User Where Id = : UserInfo.getUserId()];
 ElasticEmail.sendEmail(u); 
 }

}




Ruby

#!/usr/bin/env ruby
require 'net/http'

USERNAME = '<Elastic Email Account Username>' 
API_KEY = '<Elastic Email Account API Key>' 
API_URI = URI.parse( 'http://api.elasticemail.com/mailer/send' )
SUCCESS_MATCH_PATTERN = '^[0-9|a-f]{8}-[0-9|a-f]{4}-[0-9|a-f]{4}-[0-9|a-f]{4}-[0-9|a-f]{12}$' 
ERROR_MATCH_PATTERN = '^Error:' 

def send_email(to_addr, subject, body_text, body_html, from_addr, from_name, reply_to_email=nil, reply_to_name=nil, channel=nil )
 msg_info = { 
 'username' => USERNAME,
 'api_key' => API_KEY,
 'from' => from_addr,
 'from_name' => from_name,
 'to' => to_addr,
 'subject' => subject,
 'body_text' => body_text,
 'body_html' => body_html,
 'reply_to' => reply_to_email,
 'reply_to_name' => reply_to_name,
 'channel' => channel 
 }
 begin
 Net::HTTP.post_form(API_URI, msg_info).body
 rescue StandardError => e
 e.message
 end
end

result = send_email('test@test.com', 'My Subject', 'Body text', '<b>Body</b> <i>HTML</i>', 'test@test.com', 'Your Name', 'donotreply@donotreply.com', 'Do not reply', 'Channel Name')
case result
 when /#{SUCCESS_MATCH_PATTERN}/: puts "Success: #{result}"
 when /#{ERROR_MATCH_PATTERN}/: puts "Failed: #{result}"
 else puts "Failed(unrecognized): #{result}"
end





Objective C (iPhone)

// requires third party library ASIHTTPRequest - http://allseeing-i.com/ASIHTTPRequest/

- (void) doSend {
 
 NSURL *url = [NSURL URLWithString:@"https://api.elasticemail.com/mailer/send"];
 
 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
 [request addPostValue:@"username" forKey:@"username"];
 [request addPostValue:@"api key" forKey:@"api_key"];
 [request addPostValue:@"from email address" forKey:@"from"];
 [request addPostValue:@"to email address" forKey:@"to"];
 [request addPostValue:@"email subject" forKey:@"subject"];
 [request addPostValue:@"email body html" forKey:@"body_html"];
 [request addPostValue:@"fileToAttach.txt" forKey:@"attachments"];
 
 [request setCompletionBlock:^{
 NSString *responseString = [request responseString];
 NSLog(@"Send Response: %@", responseString); 
 }];
 [request setFailedBlock:^{
 NSError *error = [request error];
 NSLog(@"Send Error: %@", error.localizedDescription);
 }];
 
 [request startAsynchronous];
}

Node.js

// Build POST String
var querystring = require('querystring');
var https = require('https');

function sendElasticEmail(to, subject, body_text, body_html, from, fromName) {
 // Make sure to add your username and api_key below.
 var post_data = querystring.stringify({
 'username' : 'YOUR ACCOUNT EMAIL ADDRESS',
 'api_key': 'YOUR API KEY',
 'from': from,
 'from_name' : fromName,
 'to' : to,
 'subject' : subject,
 'body_html' : body_html,
 'body_text' : body_text
 });

 // Object of options.
 var post_options = {
 host: 'api.elasticemail.com',
 path: '/mailer/send',
 port: '443',
 method: 'POST',
 headers: {
 'Content-Type': 'application/x-www-form-urlencoded',
 'Content-Length': post_data.length
 }
 };
 var result = '';
 // Create the request object.
 var post_req = https.request(post_options, function(res) {
 res.setEncoding('utf8');
 res.on('data', function (chunk) {
 result = chunk;
 });
 res.on('error', function (e) {
 result = 'Error: ' + e.message;
 });
 });

 // Post to Elastic Email
 post_req.write(post_data);
 post_req.end();
 return result;
}

sendElasticEmail('test@test.com', 'My Subject', 'My Text', 'My HTML', 'youremail@yourdomain.com', 'Your Name');



Python 3

import urllib 

import http.client #former httplib in python2

import re 



USERNAME = '<Elastic Email Account Username>' 

API_KEY = '<Elastic Email Account API Key>' 

API_SERVER = 'api.elasticemail.com'

API_URI = '/mailer/send'

SUCCESS_MATCH_PATTERN = '^[0-9|a-f]{8}-[0-9|a-f]{4}-[0-9|a-f]{4}-[0-9|a-f]{4}-[0-9|a-f]{12}$'

ERROR_MATCH_PATTERN = '^Error:'



# Function to send e-mail 

def send_email(to_addr, subject, body_text, body_html, from_addr, from_name, reply_to_email=None, reply_to_name=None, channel=None): 





 msg_info = {} 

 msg_info['username'] = USERNAME 

 msg_info['api_key'] = API_KEY 

 msg_info['from'] = from_addr 

 msg_info['from_name'] = from_name 

 msg_info['to'] = to_addr 

 msg_info['subject'] = subject 

 msg_info['body_text'] = body_text 

 msg_info['body_html'] = body_html 

 msg_info['reply_to'] = reply_to_email 

 msg_info['reply_to_name'] = reply_to_name 

 msg_info['channel'] = channel



 params = urllib.parse.urlencode(msg_info)

 headers = {'Content-type': 'application/x-www-form-urlencoded',

 'Accept': 'text/plain'}



 try: 

 # Connect to the API and send the message 

 onn = http.client.HTTPSConnection(API_SERVER) 

 conn.request('POST', API_URI, params, headers) 

 response = conn.getresponse() 



 # Read the response from the mail server, close the connection, and return the result 

 ret = response.read() 

 conn.close() 

 except Exception as e: 

 ret = str(e)



 return ret 



# Main function 

if __name__ == '__main__': 



 # Call function to send e-mail 

 result = send_email('<to_email@mail.com>',

 'Hello test',

 'Body text',

 '<b>Body</b> <i>HTML</i>',

 '<from_email@mail.com',

 '<From Name>',

 'donotreply@donotreply.com',

 'Do not reply',

 'Channel Name') 

 

 result = result.decode('UTF-8')



 # Check return value 

 if re.search(SUCCESS_MATCH_PATTERN, result): 

 print('Success: ' + result)

 elif re.search(ERROR_MATCH_PATTERN, result): 

 print(result)

 else: 

 print('Unrecognized return: ' + result)


PHP Curl Send

Please follow this link: 

https://bitbucket.org/brocseib/elasticemailclient

License

Copyright (c) 2016-2017 Elastic Email, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

If you like this article, share it with friends:

Anna Wybieralska

Related Articles

Ready to get started?

Tens of thousands of companies around the world already send their emails with Elastic Email. Join them and discover your own email superpowers.

Free 100 emails/day No credit card required