11package com .sendgrid ;
22
33import org .json .JSONObject ;
4- import com .mashape .unirest .http .*;
5- import com .mashape .unirest .http .exceptions .*;
64import com .sendgrid .smtpapi .SMTPAPI ;
7- import com .mashape .unirest .http .JsonNode ;
85
96import java .util .ArrayList ;
7+ import java .io .BufferedReader ;
8+ import java .io .InputStreamReader ;
9+ import java .io .ByteArrayInputStream ;
10+ import java .io .FileNotFoundException ;
1011import java .util .Arrays ;
1112import java .util .HashMap ;
1213import java .util .Iterator ;
13- import java .util .Scanner ;
1414import java .util .Map ;
15+ import java .io .FileInputStream ;
1516
1617import java .io .File ;
1718import java .io .InputStream ;
18- import java .io .FileInputStream ;
19- import java .io .FileNotFoundException ;
19+ import java .io .IOException ;
20+
21+ import org .apache .http .HttpResponse ;
22+ import org .apache .http .client .HttpClient ;
23+ import org .apache .http .HttpEntity ;
24+ import org .apache .http .entity .mime .MultipartEntityBuilder ;
25+ import org .apache .http .client .methods .HttpPost ;
26+ import org .apache .http .impl .client .DefaultHttpClient ;
27+ import org .apache .http .util .EntityUtils ;
28+
2029
2130public class SendGrid {
31+ private static final String PARAM_TO = "to[%d]" ;
32+ private static final String PARAM_TONAME = "toname[%d]" ;
33+ private static final String PARAM_FROM = "from" ;
34+ private static final String PARAM_FROMNAME = "fromname" ;
35+ private static final String PARAM_REPLYTO = "replyto" ;
36+ private static final String PARAM_BCC = "bcc[%d]" ;
37+ private static final String PARAM_SUBJECT = "subject" ;
38+ private static final String PARAM_HTML = "html" ;
39+ private static final String PARAM_TEXT = "text" ;
40+ private static final String PARAM_FILES = "files[%s]" ;
41+ private static final String PARAM_XSMTPAPI = "x-smtpapi" ;
42+ private static final String PARAM_HEADERS = "headers" ;
43+
2244 private String username ;
2345 private String password ;
2446 private String url ;
2547 private String port ;
2648 private String endpoint ;
49+ private HttpClient client ;
2750
2851 public SendGrid (String username , String password ) {
2952 this .username = username ;
3053 this .password = password ;
3154 this .url = "https://api.sendgrid.com" ;
3255 this .endpoint = "/api/mail.send.json" ;
56+ this .client = new DefaultHttpClient ();
3357 }
3458
3559 public SendGrid setUrl (String url ) {
@@ -42,30 +66,69 @@ public SendGrid setEndpoint(String endpoint) {
4266 return this ;
4367 }
4468
69+ public HttpEntity buildBody (Email email ) {
70+ MultipartEntityBuilder builder = MultipartEntityBuilder .create ();
71+
72+ builder .addTextBody ("api_user" , this .username );
73+ builder .addTextBody ("api_key" , this .password );
74+
75+ for (int i = 0 , len = email .getTos ().length ; i < len ; i ++)
76+ builder .addTextBody (String .format (PARAM_TO , i ), email .getTos ()[i ]);
77+
78+ for (int i = 0 , len = email .getToNames ().length ; i < len ; i ++)
79+ builder .addTextBody (String .format (PARAM_TONAME , i ), email .getToNames ()[i ]);
80+
81+ for (int i = 0 , len = email .getBccs ().length ; i < len ; i ++)
82+ builder .addTextBody (String .format (PARAM_BCC , i ), email .getBccs ()[i ]);
83+ // Files
84+ if (email .getAttachments ().size () > 0 ) {
85+ Iterator it = email .getAttachments ().entrySet ().iterator ();
86+ while (it .hasNext ()) {
87+ Map .Entry entry = (Map .Entry ) it .next ();
88+ builder .addBinaryBody (String .format (PARAM_FILES , entry .getKey ()), (InputStream ) entry .getValue ());
89+ }
90+ }
91+
92+ if (email .getHeaders ().size () > 0 )
93+ builder .addTextBody (PARAM_HEADERS , new JSONObject (email .getHeaders ()).toString ());
94+
95+ if (email .getFrom () != null && !email .getFrom ().isEmpty ())
96+ builder .addTextBody (PARAM_FROM , email .getFrom ());
97+
98+ if (email .getFromName () != null && !email .getFromName ().isEmpty ())
99+ builder .addTextBody (PARAM_FROMNAME , email .getFromName ());
100+
101+ if (email .getReplyTo () != null && !email .getReplyTo ().isEmpty ())
102+ builder .addTextBody (PARAM_REPLYTO , email .getReplyTo ());
103+
104+ if (email .getSubject () != null && !email .getSubject ().isEmpty ())
105+ builder .addTextBody (PARAM_SUBJECT , email .getSubject ());
106+
107+ if (email .getHtml () != null && !email .getHtml ().isEmpty ())
108+ builder .addTextBody (PARAM_HTML , email .getHtml ());
109+
110+ if (email .getText () != null && !email .getText ().isEmpty ())
111+ builder .addTextBody (PARAM_TEXT , email .getText ());
112+
113+ if (!email .getSMTPAPI ().jsonString ().equals ("{}" )) {
114+ builder .addTextBody (PARAM_XSMTPAPI , email .getSMTPAPI ().jsonString ());
115+ }
116+ return builder .build ();
117+ }
118+
45119 public SendGrid .Response send (Email email ) throws SendGridException {
120+ HttpPost httppost = new HttpPost (this .url + this .endpoint );
121+ httppost .setEntity (this .buildBody (email ));
46122 try {
47- HttpResponse <JsonNode > res = Unirest .post (this .url + this .endpoint )
48- .fields (email .toWebFormat ()).field ("api_user" , this .username ).field ("api_key" , this .password ).asJson ();
49- return new SendGrid .Response (res .getCode (), res .getBody ());
50- } catch (UnirestException e ) {
51- throw new SendGridException (e );
123+ HttpResponse res = this .client .execute (httppost );
124+ return new SendGrid .Response (res .getStatusLine ().getStatusCode (), EntityUtils .toString (res .getEntity ()));
125+ } catch (IOException e ) {
126+ return new SendGrid .Response (500 , "Problem connecting to SendGrid" );
52127 }
128+
53129 }
54130
55131 public static class Email {
56- private static final String PARAM_TO = "to[%d]" ;
57- private static final String PARAM_TONAME = "toname[%d]" ;
58- private static final String PARAM_FROM = "from" ;
59- private static final String PARAM_FROMNAME = "fromname" ;
60- private static final String PARAM_REPLYTO = "replyto" ;
61- private static final String PARAM_BCC = "bcc[%d]" ;
62- private static final String PARAM_SUBJECT = "subject" ;
63- private static final String PARAM_HTML = "html" ;
64- private static final String PARAM_TEXT = "text" ;
65- private static final String PARAM_FILES = "files[%s]" ;
66- private static final String PARAM_XSMTPAPI = "x-smtpapi" ;
67- private static final String PARAM_HEADERS = "headers" ;
68-
69132 private SMTPAPI smtpapi ;
70133 private ArrayList <String > to ;
71134 private ArrayList <String > toname ;
@@ -106,7 +169,7 @@ public Email setTo(String[] tos) {
106169 return this ;
107170 }
108171
109- public String [] getTo () {
172+ public String [] getTos () {
110173 return this .to .toArray (new String [this .to .size ()]);
111174 }
112175
@@ -125,7 +188,7 @@ public Email setToName(String[] tonames) {
125188 return this ;
126189 }
127190
128- public String [] getToName () {
191+ public String [] getToNames () {
129192 return this .toname .toArray (new String [this .toname .size ()]);
130193 }
131194
@@ -171,7 +234,7 @@ public Email setBcc(String[] bccs) {
171234 return this ;
172235 }
173236
174- public String [] getBcc () {
237+ public String [] getBccs () {
175238 return this .bcc .toArray (new String [this .bcc .size ()]);
176239 }
177240
@@ -254,24 +317,21 @@ public JSONObject getFilters() {
254317 return this .smtpapi .getFilters ();
255318 }
256319
257- public Email addAttachment (String name , File file ) {
258- this .attachments .put (name , file );
259- return this ;
320+ public Email addAttachment (String name , File file ) throws IOException , FileNotFoundException {
321+ return this .addAttachment (name , new FileInputStream (file ));
322+ }
323+
324+ public Email addAttachment (String name , String file ) throws IOException {
325+ return this .addAttachment (name , new ByteArrayInputStream (file .getBytes ()));
260326 }
261327
262- public Email addAttachment (String name , String file ) {
328+ public Email addAttachment (String name , InputStream file ) throws IOException {
263329 this .attachments .put (name , file );
264330 return this ;
265331 }
266332
267- public Email addAttachment (String name , InputStream file ) {
268- Scanner scanner = new Scanner (file , "UTF-8" );
269- String buffer = new String ();
270- while (scanner .hasNextLine ()) {
271- buffer += scanner .nextLine ();
272- }
273- scanner .close ();
274- return this .addAttachment (name , buffer );
333+ public Map getAttachments () {
334+ return this .attachments ;
275335 }
276336
277337 public Email addHeader (String key , String val ) {
@@ -286,64 +346,17 @@ public Map getHeaders() {
286346 public SMTPAPI getSMTPAPI () {
287347 return this .smtpapi ;
288348 }
289-
290- public Map toWebFormat () {
291- Map body = new HashMap ();
292-
293- for (int i = 0 ; i < this .to .size (); i ++)
294- body .put (String .format (PARAM_TO , i ), this .to .get (i ));
295-
296- for (int i = 0 ; i < this .toname .size (); i ++)
297- body .put (String .format (PARAM_TONAME , i ), this .toname .get (i ));
298-
299- for (int i = 0 ; i < this .bcc .size (); i ++)
300- body .put (String .format (PARAM_BCC , i ), this .bcc .get (i ));
301-
302- if (this .from != null && !this .from .isEmpty ())
303- body .put (PARAM_FROM , this .from );
304-
305- if (this .fromname != null && !this .fromname .isEmpty ())
306- body .put (PARAM_FROMNAME , this .fromname );
307-
308- if (this .replyto != null && !this .replyto .isEmpty ())
309- body .put (PARAM_REPLYTO , this .replyto );
310-
311- if (this .subject != null && !this .subject .isEmpty ())
312- body .put (PARAM_SUBJECT , this .subject );
313-
314- if (this .text != null && !this .text .isEmpty ())
315- body .put (PARAM_TEXT , this .text );
316-
317- if (this .html != null && !this .html .isEmpty ())
318- body .put (PARAM_HTML , this .html );
319-
320- if (!this .headers .isEmpty ())
321- body .put (PARAM_HEADERS , new JSONObject (this .headers ).toString ());
322-
323- if (!this .smtpapi .jsonString ().equals ("{}" ))
324- body .put (PARAM_XSMTPAPI , this .smtpapi .jsonString ());
325-
326- if (this .attachments .size () > 0 ) {
327- Iterator it = this .attachments .entrySet ().iterator ();
328- while (it .hasNext ()) {
329- Map .Entry entry = (Map .Entry ) it .next ();
330- body .put (String .format (PARAM_FILES , entry .getKey ()), entry .getValue ());
331- }
332- }
333-
334- return body ;
335- }
336349 }
337350
338351 public static class Response {
339352 private int code ;
340353 private boolean success ;
341354 private String message ;
342355
343- public Response (int code , JsonNode body ) {
356+ public Response (int code , String msg ) {
344357 this .code = code ;
345358 this .success = code == 200 ;
346- this .message = body . toString () ;
359+ this .message = msg ;
347360 }
348361
349362 public int getCode () {
0 commit comments