forked from sendgrid/sendgrid-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSendGrid.java
More file actions
492 lines (399 loc) · 15.2 KB
/
SendGrid.java
File metadata and controls
492 lines (399 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package com.sendgrid;
import com.sendgrid.smtpapi.SMTPAPI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.*;
import java.util.*;
public class SendGrid {
private static final String VERSION = "2.2.2";
private static final String USER_AGENT = "sendgrid/" + VERSION + ";java";
private static final String PARAM_TO = "to[]";
private static final String PARAM_TONAME = "toname[]";
private static final String PARAM_CC = "cc[]";
private static final String PARAM_BCC = "bcc[]";
private static final String PARAM_FROM = "from";
private static final String PARAM_FROMNAME = "fromname";
private static final String PARAM_REPLYTO = "replyto";
private static final String PARAM_SUBJECT = "subject";
private static final String PARAM_HTML = "html";
private static final String PARAM_TEXT = "text";
private static final String PARAM_FILES = "files[%s]";
private static final String PARAM_CONTENTS = "content[%s]";
private static final String PARAM_XSMTPAPI = "x-smtpapi";
private static final String PARAM_HEADERS = "headers";
private static final String TEXT_PLAIN = "text/plain";
private static final String UTF_8 = "UTF-8";
private String username;
private String password;
private String url;
private String port;
private String endpoint;
private CloseableHttpClient client;
/**
* Constructor for using a username and password
*
* @param username SendGrid username
* @param password SendGrid password
*/
public SendGrid(String username, String password) {
this.username = username;
this.password = password;
this.url = "https://api.sendgrid.com";
this.endpoint = "/api/mail.send.json";
this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
}
/**
* Constructor for using an API key
*
* @param apiKey SendGrid api key
*/
public SendGrid(String apiKey) {
this.password = apiKey;
this.username = null;
this.url = "https://api.sendgrid.com";
this.endpoint = "/api/mail.send.json";
this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
}
public SendGrid setUrl(String url) {
this.url = url;
return this;
}
public SendGrid setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public String getVersion() {
return VERSION;
}
public SendGrid setClient(CloseableHttpClient client) {
this.client = client;
return this;
}
public HttpEntity buildBody(Email email) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// We are using an API key
if (this.username != null) {
builder.addTextBody("api_user", this.username);
builder.addTextBody("api_key", this.password);
}
String[] tos = email.getTos();
String[] tonames = email.getToNames();
String[] ccs = email.getCcs();
String[] bccs = email.getBccs();
// If SMTPAPI Header is used, To is still required. #workaround.
if (tos.length == 0) {
builder.addTextBody(String.format(PARAM_TO, 0), email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8));
}
for (int i = 0, len = tos.length; i < len; i++)
builder.addTextBody(PARAM_TO, tos[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = tonames.length; i < len; i++)
builder.addTextBody(PARAM_TONAME, tonames[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = ccs.length; i < len; i++)
builder.addTextBody(PARAM_CC, ccs[i], ContentType.create("text/plain", "UTF-8"));
for (int i = 0, len = bccs.length; i < len; i++)
builder.addTextBody(PARAM_BCC, bccs[i], ContentType.create(TEXT_PLAIN, UTF_8));
// Files
if (email.getAttachments().size() > 0) {
Iterator it = email.getAttachments().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
builder.addBinaryBody(String.format(PARAM_FILES, entry.getKey()), (InputStream) entry.getValue());
}
}
if (email.getContentIds().size() > 0) {
Iterator it = email.getContentIds().entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
builder.addTextBody(String.format(PARAM_CONTENTS, entry.getKey()), (String) entry.getValue());
}
}
if (email.getHeaders().size() > 0)
builder.addTextBody(PARAM_HEADERS, new JSONObject(email.getHeaders()).toString(), ContentType.create(TEXT_PLAIN, UTF_8));
if (email.getFrom() != null && !email.getFrom().isEmpty())
builder.addTextBody(PARAM_FROM, email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8));
if (email.getFromName() != null && !email.getFromName().isEmpty())
builder.addTextBody(PARAM_FROMNAME, email.getFromName(), ContentType.create(TEXT_PLAIN, UTF_8));
if (email.getReplyTo() != null && !email.getReplyTo().isEmpty())
builder.addTextBody(PARAM_REPLYTO, email.getReplyTo(), ContentType.create(TEXT_PLAIN, UTF_8));
if (email.getSubject() != null && !email.getSubject().isEmpty())
builder.addTextBody(PARAM_SUBJECT, email.getSubject(), ContentType.create(TEXT_PLAIN, UTF_8));
if (email.getHtml() != null && !email.getHtml().isEmpty())
builder.addTextBody(PARAM_HTML, email.getHtml(), ContentType.create(TEXT_PLAIN, UTF_8));
if (email.getText() != null && !email.getText().isEmpty())
builder.addTextBody(PARAM_TEXT, email.getText(), ContentType.create(TEXT_PLAIN, UTF_8));
String tmpString = email.smtpapi.jsonString();
if (!tmpString.equals("{}"))
builder.addTextBody(PARAM_XSMTPAPI, tmpString, ContentType.create(TEXT_PLAIN, UTF_8));
return builder.build();
}
public SendGrid.Response send(Email email) throws SendGridException {
HttpPost httppost = new HttpPost(this.url + this.endpoint);
httppost.setEntity(this.buildBody(email));
// Using an API key
if (this.username == null) {
httppost.setHeader("Authorization", "Bearer " + this.password);
}
try {
HttpResponse res = this.client.execute(httppost);
return new SendGrid.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
} catch (IOException e) {
throw new SendGridException(e);
}
}
public static class Email {
private SMTPAPI smtpapi;
private ArrayList<String> to;
private ArrayList<String> toname;
private ArrayList<String> cc;
private String from;
private String fromname;
private String replyto;
private String subject;
private String text;
private String html;
private ArrayList<String> bcc;
private Map<String, InputStream> attachments;
private Map<String, String> contents;
private Map<String, String> headers;
public Email() {
this.smtpapi = new SMTPAPI();
this.to = new ArrayList<String>();
this.toname = new ArrayList<String>();
this.cc = new ArrayList<String>();
this.bcc = new ArrayList<String>();
this.attachments = new HashMap<String, InputStream>();
this.contents = new HashMap<String, String>();
this.headers = new HashMap<String, String>();
}
public Email addTo(String to) {
this.to.add(to);
return this;
}
public Email addTo(String[] tos) {
this.to.addAll(Arrays.asList(tos));
return this;
}
public Email addTo(String to, String name) {
this.addTo(to);
return this.addToName(name);
}
public Email setTo(String[] tos) {
this.to = new ArrayList<String>(Arrays.asList(tos));
return this;
}
public String[] getTos() {
return this.to.toArray(new String[this.to.size()]);
}
public Email addSmtpApiTo(String to) {
this.smtpapi.addTo(to);
return this;
}
public Email addSmtpApiTo(String[] to) {
this.smtpapi.addTos(to);
return this;
}
public Email addToName(String toname) {
this.toname.add(toname);
return this;
}
public Email addToName(String[] tonames) {
this.toname.addAll(Arrays.asList(tonames));
return this;
}
public Email setToName(String[] tonames) {
this.toname = new ArrayList<String>(Arrays.asList(tonames));
return this;
}
public String[] getToNames() {
return this.toname.toArray(new String[this.toname.size()]);
}
public Email addCc(String cc) {
this.cc.add(cc);
return this;
}
public Email addCc(String[] ccs) {
this.cc.addAll(Arrays.asList(ccs));
return this;
}
public Email setCc(String[] ccs) {
this.cc = new ArrayList<String>(Arrays.asList(ccs));
return this;
}
public String[] getCcs() {
return this.cc.toArray(new String[this.cc.size()]);
}
public Email setFrom(String from) {
this.from = from;
return this;
}
public String getFrom() {
return this.from;
}
public Email setFromName(String fromname) {
this.fromname = fromname;
return this;
}
public String getFromName() {
return this.fromname;
}
public Email setReplyTo(String replyto) {
this.replyto = replyto;
return this;
}
public String getReplyTo() {
return this.replyto;
}
public Email addBcc(String bcc) {
this.bcc.add(bcc);
return this;
}
public Email addBcc(String[] bccs) {
this.bcc.addAll(Arrays.asList(bccs));
return this;
}
public Email setBcc(String[] bccs) {
this.bcc = new ArrayList<String>(Arrays.asList(bccs));
return this;
}
public String[] getBccs() {
return this.bcc.toArray(new String[this.bcc.size()]);
}
public Email setSubject(String subject) {
this.subject = subject;
return this;
}
public String getSubject() {
return this.subject;
}
public Email setText(String text) {
this.text = text;
return this;
}
public String getText() {
return this.text;
}
public Email setHtml(String html) {
this.html = html;
return this;
}
public String getHtml() {
return this.html;
}
public Email addSubstitution(String key, String[] val) {
this.smtpapi.addSubstitutions(key, val);
return this;
}
public JSONObject getSubstitutions() {
return this.smtpapi.getSubstitutions();
}
public Email addUniqueArg(String key, String val) {
this.smtpapi.addUniqueArg(key, val);
return this;
}
public JSONObject getUniqueArgs() {
return this.smtpapi.getUniqueArgs();
}
public Email addCategory(String category) {
this.smtpapi.addCategory(category);
return this;
}
public String[] getCategories() {
return this.smtpapi.getCategories();
}
public Email addSection(String key, String val) {
this.smtpapi.addSection(key, val);
return this;
}
public JSONObject getSections() {
return this.smtpapi.getSections();
}
public Email addFilter(String filter_name, String parameter_name, String parameter_value) {
this.smtpapi.addFilter(filter_name, parameter_name, parameter_value);
return this;
}
public JSONObject getFilters() {
return this.smtpapi.getFilters();
}
public Email setASMGroupId(int val) {
this.smtpapi.setASMGroupId(val);
return this;
}
public Integer getASMGroupId() {
return this.smtpapi.getASMGroupId();
}
public Email setSendAt(int sendAt) {
this.smtpapi.setSendAt(sendAt);
return this;
}
public int getSendAt() {
return this.smtpapi.getSendAt();
}
/**
* Convenience method to set the template
*
* @param templateId The ID string of your template
* @return this
*/
public Email setTemplateId(String templateId) {
this.getSMTPAPI().addFilter("templates", "enable", 1);
this.getSMTPAPI().addFilter("templates", "template_id", templateId);
return this;
}
public Email addAttachment(String name, File file) throws IOException, FileNotFoundException {
return this.addAttachment(name, new FileInputStream(file));
}
public Email addAttachment(String name, String file) throws IOException {
return this.addAttachment(name, new ByteArrayInputStream(file.getBytes()));
}
public Email addAttachment(String name, InputStream file) throws IOException {
this.attachments.put(name, file);
return this;
}
public Map getAttachments() {
return this.attachments;
}
public Email addContentId(String attachmentName, String cid) {
this.contents.put(attachmentName, cid);
return this;
}
public Map getContentIds() {
return this.contents;
}
public Email addHeader(String key, String val) {
this.headers.put(key, val);
return this;
}
public Map getHeaders() {
return this.headers;
}
public SMTPAPI getSMTPAPI() {
return this.smtpapi;
}
}
public static class Response {
private int code;
private boolean success;
private String message;
public Response(int code, String msg) {
this.code = code;
this.success = code == 200;
this.message = msg;
}
public int getCode() {
return this.code;
}
public boolean getStatus() {
return this.success;
}
public String getMessage() {
return this.message;
}
}
}