Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
14534 manish.sha 1
package in.shop2020.inventory.service;
2
 
3
import org.json.JSONException;
4
import org.json.JSONObject;
5
import com.sendgrid.smtpapi.SMTPAPI;
6
 
7
import java.util.ArrayList;
8
import java.io.BufferedReader;
9
import java.io.InputStreamReader;
10
import java.io.ByteArrayInputStream;
11
import java.io.FileNotFoundException;
12
import java.util.Arrays;
13
import java.util.HashMap;
14
import java.util.Iterator;
15
import java.util.Map;
16
import java.io.FileInputStream;
17
 
18
import java.io.File;
19
import java.io.InputStream;
20
import java.io.IOException;
21
 
22
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
27
import org.apache.http.impl.client.CloseableHttpClient;
28
import org.apache.http.util.EntityUtils;
29
import org.apache.http.entity.ContentType;
30
 
31
public class SendGrid {
32
  private static final String VERSION           = "1.2.0";
33
  private static final String USER_AGENT        = "sendgrid/" + VERSION + ";java";
34
 
35
  private static final String PARAM_TO          = "to[%d]";
36
  private static final String PARAM_TONAME      = "toname[%d]";
37
  private static final String PARAM_CC          = "cc[%d]";
38
  private static final String PARAM_FROM        = "from";
39
  private static final String PARAM_FROMNAME    = "fromname";
40
  private static final String PARAM_REPLYTO     = "replyto";
41
  private static final String PARAM_BCC         = "bcc[%d]";
42
  private static final String PARAM_SUBJECT     = "subject";
43
  private static final String PARAM_HTML        = "html";
44
  private static final String PARAM_TEXT        = "text";
45
  private static final String PARAM_FILES       = "files[%s]";
46
  private static final String PARAM_XSMTPAPI    = "x-smtpapi";
47
  private static final String PARAM_HEADERS     = "headers";
48
 
49
  private String username;
50
  private String password;
51
  private String url;
52
  private String port;
53
  private String endpoint;
54
  private CloseableHttpClient client;
55
 
56
  public SendGrid(String username, String password) {
57
    this.username = username;
58
    this.password = password;
59
    this.url = "https://api.sendgrid.com";
60
    this.endpoint = "/api/mail.send.json";
61
    this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
62
  }
63
 
64
  public SendGrid setUrl(String url) {
65
    this.url = url;
66
    return this;
67
  }
68
 
69
  public SendGrid setEndpoint(String endpoint) {
70
    this.endpoint = endpoint;
71
    return this;
72
  }
73
 
74
  public String getVersion() {
75
    return VERSION;
76
  }
77
 
78
  public SendGrid setClient(CloseableHttpClient client) {
79
    this.client = client;
80
    return this;
81
  }
82
 
83
  public HttpEntity buildBody(Email email) {
84
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
85
 
86
    builder.addTextBody("api_user", this.username);
87
    builder.addTextBody("api_key", this.password);
88
 
89
    String[] tos = email.getTos();
90
    String[] tonames = email.getToNames();
91
    String[] ccs = email.getCcs();
92
    String[] bccs = email.getBccs();
93
 
94
    for (int i = 0, len = tos.length; i < len; i++)
95
      builder.addTextBody(String.format(PARAM_TO, i), tos[i]);
96
    for (int i = 0, len = tonames.length; i < len; i++)
97
      builder.addTextBody(String.format(PARAM_TONAME, i), tonames[i], ContentType.create("text/plain", "UTF-8"));
98
    for (int i = 0, len = ccs.length; i < len; i++)
99
      builder.addTextBody(String.format(PARAM_CC, i), ccs[i]);
100
    for (int i = 0, len = bccs.length; i < len; i++)
101
      builder.addTextBody(String.format(PARAM_BCC, i), bccs[i]);
102
    // Files
103
    if (email.getAttachments().size() > 0) {
104
      Iterator it = email.getAttachments().entrySet().iterator();
105
      while (it.hasNext()) {
106
        Map.Entry entry = (Map.Entry) it.next();
107
        builder.addBinaryBody(String.format(PARAM_FILES, entry.getKey()), (InputStream) entry.getValue());
108
      }
109
    }
110
 
111
    if (email.getHeaders().size() > 0)
112
      builder.addTextBody(PARAM_HEADERS, new JSONObject(email.getHeaders()).toString());
113
 
114
    if (email.getFrom() != null && !email.getFrom().isEmpty())
115
      builder.addTextBody(PARAM_FROM, email.getFrom());
116
 
117
    if (email.getFromName() != null && !email.getFromName().isEmpty())
118
      builder.addTextBody(PARAM_FROMNAME, email.getFromName(), ContentType.create("text/plain", "UTF-8"));
119
 
120
    if (email.getReplyTo() != null && !email.getReplyTo().isEmpty())
121
      builder.addTextBody(PARAM_REPLYTO, email.getReplyTo());
122
 
123
    if (email.getSubject() != null && !email.getSubject().isEmpty())
124
      builder.addTextBody(PARAM_SUBJECT, email.getSubject(), ContentType.create("text/plain", "UTF-8"));
125
 
126
    if (email.getHtml() != null && !email.getHtml().isEmpty())
127
      builder.addTextBody(PARAM_HTML, email.getHtml(), ContentType.create("text/plain", "UTF-8"));
128
 
129
    if (email.getText() != null && !email.getText().isEmpty())
130
      builder.addTextBody(PARAM_TEXT, email.getText(), ContentType.create("text/plain", "UTF-8"));
131
 
132
    if (!email.getSMTPAPI().jsonString().equals("{}"))
133
      builder.addTextBody(PARAM_XSMTPAPI, email.getSMTPAPI().jsonString());
134
 
135
    return builder.build();
136
  }
137
 
138
  public SendGrid.Response send(Email email) throws SendGridException {
139
    HttpPost httppost = new HttpPost(this.url + this.endpoint);
140
    httppost.setEntity(this.buildBody(email));
141
    try {
142
      HttpResponse res = this.client.execute(httppost);
143
      return new SendGrid.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
144
    } catch (IOException e) {
145
      return new SendGrid.Response(500, "Problem connecting to SendGrid");
146
    }
147
 
148
  }
149
 
150
  public static class Email {
151
    private SMTPAPI smtpapi;
152
    private ArrayList<String> to;
153
    private ArrayList<String> toname;
154
    private ArrayList<String> cc;
155
    private String from;
156
    private String fromname;
157
    private String replyto;
158
    private String subject;
159
    private String text;
160
    private String html;
161
    private ArrayList<String> bcc;
162
    private Map<String, InputStream> attachments;
163
    private Map<String, String> headers;
164
 
165
    public Email () {
166
      this.smtpapi = new SMTPAPI();
167
      this.to = new ArrayList<String>();
168
      this.toname = new ArrayList<String>();
169
      this.cc = new ArrayList<String>();
170
      this.bcc = new ArrayList<String>();
171
      this.attachments = new HashMap<String, InputStream>();
172
      this.headers = new HashMap<String, String>();
173
    }
174
 
175
    public Email addTo(String to) throws JSONException {
176
      this.smtpapi.addTo(to);
177
      this.to.add(to);
178
      return this;
179
    }
180
 
181
    public Email addTo(String[] tos) throws JSONException {
182
      this.smtpapi.addTos(tos);
183
      this.to.addAll(Arrays.asList(tos));
184
      return this;
185
    }
186
 
187
    public Email addTo(String to, String name) throws JSONException {
188
      this.addTo(to);
189
      return this.addToName(name);
190
    }
191
 
192
    public Email setTo(String[] tos) throws JSONException {
193
      this.smtpapi.setTos(tos);
194
      this.to = new ArrayList<String>(Arrays.asList(tos));
195
      return this;
196
    }
197
 
198
    public String[] getTos() {
199
      return this.to.toArray(new String[this.to.size()]);
200
    }
201
 
202
    public Email addToName(String toname) {
203
      this.toname.add(toname);
204
      return this;
205
    }
206
 
207
    public Email addToName(String[] tonames) {
208
      this.toname.addAll(Arrays.asList(tonames));
209
      return this;
210
    }
211
 
212
    public Email setToName(String[] tonames) {
213
      this.toname = new ArrayList<String>(Arrays.asList(tonames));
214
      return this;
215
    }
216
 
217
    public String[] getToNames() {
218
      return this.toname.toArray(new String[this.toname.size()]);
219
    }
220
 
221
    public Email addCc(String cc) {
222
      this.cc.add(cc);
223
      return this;
224
    }
225
 
226
    public Email addCc(String[] ccs) {
227
      this.cc.addAll(Arrays.asList(ccs));
228
      return this;
229
    }
230
 
231
    public Email setCc(String[] ccs) {
232
      this.cc = new ArrayList<String>(Arrays.asList(ccs));
233
      return this;
234
    }
235
 
236
    public String[] getCcs() {
237
      return this.cc.toArray(new String[this.cc.size()]);
238
    }
239
 
240
    public Email setFrom(String from) {
241
      this.from = from;
242
      return this;
243
    }
244
 
245
    public String getFrom() {
246
      return this.from;
247
    }
248
 
249
    public Email setFromName(String fromname) {
250
      this.fromname = fromname;
251
      return this;
252
    }
253
 
254
    public String getFromName() {
255
      return this.fromname;
256
    }
257
 
258
    public Email setReplyTo(String replyto) {
259
      this.replyto = replyto;
260
      return this;
261
    }
262
 
263
    public String getReplyTo() {
264
      return this.replyto;
265
    }
266
 
267
    public Email addBcc(String bcc) {
268
      this.bcc.add(bcc);
269
      return this;
270
    }
271
 
272
    public Email addBcc(String[] bccs) {
273
      this.bcc.addAll(Arrays.asList(bccs));
274
      return this;
275
    }
276
 
277
    public Email setBcc(String[] bccs) {
278
      this.bcc = new ArrayList<String>(Arrays.asList(bccs));
279
      return this;
280
    }
281
 
282
    public String[] getBccs() {
283
      return this.bcc.toArray(new String[this.bcc.size()]);
284
    }
285
 
286
    public Email setSubject(String subject) {
287
      this.subject = subject;
288
      return this;
289
    }
290
 
291
    public String getSubject() {
292
      return this.subject;
293
    }
294
 
295
    public Email setText(String text) {
296
      this.text = text;
297
      return this;
298
    }
299
 
300
    public String getText() {
301
      return this.text;
302
    }
303
 
304
    public Email setHtml(String html) {
305
      this.html = html;
306
      return this;
307
    }
308
 
309
    public String getHtml() {
310
      return this.html;
311
    }
312
 
313
    public Email dropSMTPAPITos() throws JSONException {
314
      JSONObject oldHeader = new JSONObject(this.smtpapi.jsonString());
315
      oldHeader.remove("to");
316
      this.smtpapi = new SMTPAPI(oldHeader);
317
      return this;
318
    }
319
 
320
    public Email addSubstitution(String key, String[] val) throws JSONException {
321
      this.smtpapi.addSubstitutions(key, val);
322
      return this;
323
    }
324
 
325
    public JSONObject getSubstitutions() throws JSONException {
326
      return this.smtpapi.getSubstitutions();
327
    }
328
 
329
    public Email addUniqueArg(String key, String val) throws JSONException {
330
      this.smtpapi.addUniqueArg(key, val);
331
      return this;
332
    }
333
 
334
    public JSONObject getUniqueArgs() throws JSONException {
335
      return this.smtpapi.getUniqueArgs();
336
    }
337
 
338
    public Email addCategory(String category) throws JSONException {
339
      this.smtpapi.addCategory(category);
340
      return this;
341
    }
342
 
343
    public String[] getCategories() throws JSONException {
344
      return this.smtpapi.getCategories();
345
    }
346
 
347
    public Email addSection(String key, String val) throws JSONException {
348
      this.smtpapi.addSection(key, val);
349
      return this;
350
    }
351
 
352
    public JSONObject getSections() throws JSONException {
353
      return this.smtpapi.getSections();
354
    }
355
 
356
    public Email addFilter(String filter_name, String parameter_name, String parameter_value) throws JSONException {
357
      this.smtpapi.addFilter(filter_name, parameter_name, parameter_value);
358
      return this;
359
    }
360
 
361
    public JSONObject getFilters() throws JSONException {
362
      return this.smtpapi.getFilters();
363
    }
364
 
365
    public Email addAttachment(String name, File file) throws IOException, FileNotFoundException {
366
      return this.addAttachment(name, new FileInputStream(file));
367
    }
368
 
369
    public Email addAttachment(String name, String file) throws IOException {
370
      return this.addAttachment(name, new ByteArrayInputStream(file.getBytes()));
371
    }
372
 
373
    public Email addAttachment(String name, InputStream file) throws IOException {
374
      this.attachments.put(name, file);
375
      return this;
376
    }
377
 
378
    public Map getAttachments() {
379
      return this.attachments;
380
    }
381
 
382
    public Email addHeader(String key, String val) {
383
      this.headers.put(key, val);
384
      return this;
385
    }
386
 
387
    public Map getHeaders() {
388
      return this.headers;
389
    }
390
 
391
    public SMTPAPI getSMTPAPI() {
392
      return this.smtpapi;
393
    }
394
  }
395
 
396
  public static class Response {
397
    private int code;
398
    private boolean success;
399
    private String message;
400
 
401
    public Response(int code, String msg) {
402
      this.code = code;
403
      this.success = code == 200;
404
      this.message = msg;
405
    }
406
 
407
    public int getCode() {
408
      return this.code;
409
    }
410
 
411
    public boolean getStatus() {
412
      return this.success;
413
    }
414
 
415
    public String getMessage() {
416
      return this.message;
417
    }
418
  }
419
}