Send Email with Attachments

Learn how to send email with attachments via Elastic Email API.

Overview

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.

C#

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

namespace ElasticEmailClient
{
    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("bodyHtml", "<h1>Html Body</h1>");
            
            string address = "https://api.elasticemail.com/v2/email/send";

            var filepath = "C:\\example\\helloWorld.txt";
            var file = File.OpenRead(filepath);

            var filesStream = new Stream[] { file };
            var filenames = new string[] { "filenameForInbox.txt" };
            var URL = "https://api.elasticemail.com/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;
            }
        }

    }
}

PHP

<?php
$url = 'https://api.elasticemail.com/v2/email/send';
$filename = "helloWorld.txt";
$file_name_with_full_path = realpath('./'.$filename);
$filetype = "text/plain"; // Change correspondingly to the file type

try{
        $post = array('from' => 'youremail@yourdomain.com',
                      'fromName' => 'Your Company Name',
                      'apikey' => '00000000-0000-0000-0000-000000000000',
                      'subject' => 'Your Subject',
                      'bodyHtml' => '&lt;h1&gt;Html Body&lt;/h1&gt;',
                      'bodyText' => 'Text Body',
                      '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();
}
?>

Java

--------------ElasticClient.java--------
package com.elasticemail.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();
        ArrayList<FileData>files = 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<String, String> 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", "Text Body");
        values.put("bodyHtml", "&lt;h1&gt;Html Body&lt;/h1&gt;");
        
        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.elasticemail.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 = "https://api.elasticemail.com/v2";

    protected String httpPostFile(String targetURL, Iterable<FileData> fileData, Map<String, String> 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<String, String> 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.elasticemail.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;
    }
}

Python

import requests
import json
from enum import Enum

class ApiClient:
    apiUri = 'https://api.elasticemail.com/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/helloWorld.txt')
print(Send("Your Subject", "youremail@yourdomain.com", "Your Company Name", "&lt;h1&gt;Html Body&lt;/h1&gt;", "Text Body", True, "someFilename.txt", attachments))

License

All code samples are licensed under MIT license.