by Jarek Dec 2, 2016

Check out how to upload attachments using HTTP API V1.

This is a deprecated API Call. For Updated API Documentation Visit: http://api.elasticemail.com/public/help

The upload attachment command is used to upload an attachment for sending.

To upload your attachment do HTTP PUT of your attachment file to:

https://api.elasticemail.com/attachments/upload?username=yourusername&api_key=yourapikey&file=yourfilename

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

Once your attachment has been uploaded you will receive an attachment ID back from the request. You can send one or more attachments in your email by referencing the attachment IDs returned. You may use the attachment for up to 48 hours after it has been uploaded. Just add an attachments field to your /mailer/send call:

attachments=semi-colon separated list of attachment IDs.

See the modified code samples below which include uploading attachments.

Code Samples

PHP

<?php

$username = urlencode("YOUR ACCOUNT EMAIL ADDRESS");
$apikey = urlencode("YOUR API KEY");

function uploadAttachment($filepath, $filename) {

 global $username, $apikey;

 $data = http_build_query(array('username' => $username,'api_key' => $apikey,'file' => $filename));
 $file = file_get_contents($filepath);
 $result = ''; 

 $fp = fsockopen('ssl://api.elasticemail.com', 443, $errno, $errstr, 30); 

 if ($fp){
 fputs($fp, "PUT /attachments/upload?".$data." HTTP/1.1\r\n");
 fputs($fp, "Host: api.elasticemail.com\r\n");
 fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
 fputs($fp, "Content-length: ". strlen($file) ."\r\n");
 fputs($fp, "Connection: close\r\n\r\n");
 fputs($fp, $file);
 while(!feof($fp)) {
 $result .= fgets($fp, 128);
 }
 } else { 
 return array(
 'status'=>false,
 'error'=>$errstr.'('.$errno.')',
 'result'=>$result);
 }
 fclose($fp);
 $result = explode("\r\n\r\n", $result, 2); 
 return array(
 'status' => true,
 'attachId' => isset($result[1]) ? $result[1] : ''
 );
}

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

 global $username, $apikey;

 $res = "";

 $data = "username=".$username;
 $data .= "&api_key=".$apikey;
 $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);

 if($attachments)
 $data .= "&attachments=".urlencode($attachments);

 $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);

 if(!$fp)
 return "ERROR. Could not open connection";
 else {
 fputs ($fp, $header.$data);
 while (!feof($fp)) {
 $res .= fread ($fp, 1024);
 }
 fclose($fp);
 }
 return $res; 
}

$attach = uploadAttachment("./test.jpg", "test.jpg");
echo sendElasticEmail("test@test.com", "My Subject", "My Text", "My HTML", "you@yourdomain.com", "Your Name", $attach['attachId']);

?>

C#

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.IO;

namespace APITest
{
 class Program
 {
 public static string USERNAME = "YOUR ACCOUNT EMAIL ADDRESS";
 public static string API_KEY = "YOUR API KEY";


 static void Main(string[] args)
 {
 string from = "samplefrom@yourdomain.com";
 string fromName = "Your Company Name";
 string recipients = "recipient1@gmail.com;recipient2@hotmail.com;recipient3@yahoo.com";
 string subject = "This is a test message.";
 string bodyHtml = "This is the body of the test message. ";

 //once an attachment has been uploaded once you can use it in multiple calls to send elastic email.
 string attachment = UploadAttachment(@"D:\Pictures\test-attachment.jpg", "test.jpg");

 string result = SendElasticEmail(from, recipients, fromName, subject, bodyHtml, attachment);

 Console.WriteLine(result);
 Console.ReadKey();
 }

 public static string SendElasticEmail(string from, string to, string fromName, string subject, string bodyHtml, string attachments)
 {
 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);
 values.Add("body_html", bodyHtml);
 values.Add("to", to);
 if (attachments != null)
 values.Add("attachments", attachments);
 byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values);
 return Encoding.UTF8.GetString(response);
 }

 public static string UploadAttachment(string filepath, string filename)
 {
 FileStream stream = File.OpenRead(filepath);
 WebRequest request = WebRequest.Create("https://api.elasticemail.com/attachments/upload?username=" + USERNAME + "&api_key=" + API_KEY + "&file=" + filename);
 request.Method = "PUT";
 request.ContentLength = stream.Length;
 Stream outstream = request.GetRequestStream();
 stream.CopyTo(outstream, 4096);
 stream.Close();
 WebResponse response = request.GetResponse();
 string result = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
 response.Close();
 return result;
 }


 }
}

Objective C (iPhone)

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

- (void) doUpload
{
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"fileToAttach.txt"];
 
 NSURL *url = [NSURL URLWithString:@"https://api.elasticemail.com/attachments/upload"];
 
 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
 [request addPostValue:@"USERNAME" forKey:@"username"];
 [request addPostValue:@"API_KEY" forKey:@"api_key"];
 [request addPostValue:appFile forKey:@"file"];
 [request setFile:appFile forKey:@"file"];
 
 [request setCompletionBlock:^{
 NSString *responseString = [request responseString];
 NSLog(@"Upload Response: %@", responseString);
 
 [self doSend];
 }];
 [request setFailedBlock:^{
 NSError *error = [request error];
 NSLog(@"Upload Error: %@", error.localizedDescription);
 }];
 
 [request startAsynchronous];
 
}

- (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);
 
 [self doSend];
 }];
 [request setFailedBlock:^{
 NSError *error = [request error];
 NSLog(@"Send Error: %@", error.localizedDescription);
 }];
 
 [request startAsynchronous];
}

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:

author default image

Jarek

Member of the Customer Success Team. Don't hesitate to ask me, if you have any questions related to Elastic Email.

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.

Icon green check Instant setup Icon green check No credit card required