· 8 years ago · Nov 22, 2017, 05:38 PM
1public abstract class Abstract_Mail {
2
3@Value("${general.Mail.sAddressDefaultFrom}")
4private String sFrom; //"noreplay@gmail.com";
5@Value("${general.Mail.sAddressNoreply}")
6private String saTo; //"noreplay@gmail.com";
7private String sToName; //"Ðндрій Хветкевич";
8private String sHead = "Subject";
9private String sBody = "Text";
10@Value("${general.Mail.sUsername}")
11private String sAuthUser; //"user";
12@Value("${general.Mail.sPassword}")
13private String sAuthPassword; //"password";
14@Value("${general.Mail.sHost}")
15private String sHost; //"gmail.com";
16@Value("${general.Mail.nPort}")
17private Integer nPort; //Integer.valueOf(mailServerPort);
18@Value("${general.Mail.bUseSSL}")
19private boolean bSSL;
20@Value("${general.Mail.bUseTLS}")
21private boolean bTLS;
22public Abstract_Mail() {
23}
24
25public String getFrom() {
26 return sFrom;
27}
28
29public Abstract_Mail _From(String sFrom) {
30 this.sFrom = sFrom;
31 return this;
32}
33
34public String getTo() {
35 String[] adress = saTo.split("\,");
36 if (adress.length == 1 && sToName != null &&
37 !"null".equalsIgnoreCase(sToName)) {
38 return sToName + "<" + saTo + ">";
39 }
40 return saTo;
41}
42
43public Abstract_Mail _To(String saTo) {
44 this.saTo = saTo;
45 return this;
46}
47
48public String getToName() {
49 return sToName;
50}
51
52public Abstract_Mail _ToName(String ... saToName){
53 String fullName = saToName[0];
54 if (saToName.length > 1) {
55 for (int i = 1; i < saToName.length; i++) {
56 fullName = fullName + " " + saToName[i];
57 }
58 }
59 this.sToName = fullName;
60 return this;
61}
62
63public String getHead() {
64 return sHead;
65}
66
67public Abstract_Mail _Head(String sHead) {
68 this.sHead = sHead;
69 return this;
70}
71
72public String getBody() {
73 return sBody;
74}
75
76public Abstract_Mail _Body(String sBody) {
77 this.sBody = sBody;
78 return this;
79}
80
81public String getAuthUser() {
82 return sAuthUser;
83}
84
85public Abstract_Mail _AuthUser(String sAuthUser) {
86 this.sAuthUser = sAuthUser;
87 return this;
88}
89
90public String getAuthPassword() {
91 return sAuthPassword;
92}
93
94public Abstract_Mail _AuthPassword(String sAuthPassword) {
95 this.sAuthPassword = sAuthPassword;
96 return this;
97}
98
99public String getHost() {
100 return sHost;
101}
102
103public Abstract_Mail _Host(String sHost) {
104 this.sHost = sHost;
105 return this;
106}
107
108public Integer getPort() {
109 return nPort;
110}
111
112public Abstract_Mail _Port(Integer nPort) {
113 this.nPort = nPort;
114 return this;
115}
116
117public boolean isSSL() {
118 return bSSL;
119}
120
121public Abstract_Mail _SSL(boolean bSSL) {
122 this.bSSL = bSSL;
123 return this;
124}
125
126public boolean isTLS() {
127 return bTLS;
128}
129
130public Abstract_Mail _TLS(boolean bTLS) {
131 this.bTLS = bTLS;
132 return this;
133}
134
135abstract public void send() throws Exception;
136
137@Service("mail")
138@Scope("prototype")
139public class Mail extends Abstract_Mail {
140
141@Autowired
142MethodsCallRunnerUtil methodCallRunner;
143
144@Autowired
145GeneralConfig generalConfig;
146
147@Autowired
148UniSender oUniSender;
149
150
151private final static Logger LOG = LoggerFactory.getLogger(Mail.class);
152private static final Logger LOG_BIG = LoggerFactory.getLogger("MailBig");
153
154Properties oProps = new Properties();
155String DEFAULT_ENCODING = "UTF-8";
156private Session oSession = null;
157//private String sContext="";
158private Multipart oMultiparts = new MimeMultipart();
159
160public Mail() {
161}
162
163@Override
164public void send() throws EmailException {
165 LOG.info("send mail started...");
166 LOG.info("(getFrom()={})", getFrom());
167 LOG.info("(getTo()={})", getTo());
168 String sTo = getTo();
169 String sToNew = sTo;
170 sToNew = sToNew.replace(""", "");
171 sToNew = sToNew.replace(""", "");
172 if (!sToNew.equals(sTo)) {
173 LOG.info("(getTo()(fixed)={})", sToNew);
174 _To(sToNew);
175 }
176 LOG.info("(getHead()={})", getHead());
177
178 Boolean bUniSender = generalConfig.isEnable_UniSender_Mail();
179 LOG.info("(bUniSender={})", bUniSender);
180 LOG_BIG.info("(bUniSender={})", bUniSender);
181 LOG_BIG.debug("(getFrom()={})", getFrom());
182 LOG_BIG.debug("(getTo()={})", getTo());
183 LOG_BIG.debug("(getHead()={})", getHead());
184 LOG_BIG.debug("(getBody={})", getBody());
185
186 StringBuilder sbBody = new StringBuilder(500);
187 sbBody.append("host: ");
188 sbBody.append(getHost());
189 sbBody.append(":");
190 sbBody.append(getPort());
191 sbBody.append("nAuthUser:");
192 sbBody.append(getAuthUser());
193 sbBody.append("nfrom:");
194 sbBody.append(getFrom());
195 sbBody.append("nto:");
196 sbBody.append(getTo());
197 sbBody.append("nhead:");
198 sbBody.append(getHead());
199
200 if (bUniSender) {
201 try {
202 if (!sendWithUniSender()) {
203 sendAlternativeWay(sbBody.toString());
204 }
205 } catch (Exception oException) {
206 LOG.warn("Try send via alter channel! (getTo()={})",
207 oException.getMessage(), getTo());
208 LOG.trace("FAIL:", oException);
209 try {
210 //msgService.setEventSystem("WARNING", null, null,
211 "sendWithUniSender", "Error send via UniSender", sbBody.toString(),
212 oException.getMessage(), null);
213 } catch (Exception e) {
214
215 }
216 sendAlternativeWay(sbBody.toString());
217 }
218 } else {
219 sendAlternativeWay(sbBody.toString());
220 }
221
222 LOG.info("send mail ended ehith sbBody: " + sbBody.toString());
223}
224
225public void sendOld() throws EmailException {
226 LOG.info("sendOld started...");
227 LOG.info("init");
228 try {
229 MultiPartEmail oMultiPartEmail = new MultiPartEmail();
230 LOG.info("(getHost()={})", getHost());
231 oMultiPartEmail.setHostName(getHost());
232
233 String[] asTo = { sMailOnly(getTo()) };
234 if (getTo().contains("\,")) {
235 asTo = getTo().split("\,");//sTo
236 for (String s : asTo) {
237 LOG.info("oMultiPartEmail.addTo (s={})", s);
238 oMultiPartEmail.addTo(s, "receiver");
239 }
240 }
241
242 LOG.info("(getFrom()={})", getFrom());
243 LOG_BIG.debug("(getFrom()={})", getFrom());
244 oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
245 oMultiPartEmail.setSubject(getHead());
246 LOG.info("getHead()={}", getHead());
247 String sLogin = getAuthUser();
248 if (sLogin != null && !"".equals(sLogin.trim())) {
249 oMultiPartEmail.setAuthentication(sLogin, getAuthPassword());
250 LOG.info("withAuth");
251 } else {
252 LOG.info("withoutAuth");
253 }
254 //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
255 LOG.info("(getAuthUser()={})", getAuthUser());
256 //LOG.info("getAuthPassword()=" + getAuthPassword());
257 oMultiPartEmail.setSmtpPort(getPort());
258 LOG.info("(getPort()={})", getPort());
259 oMultiPartEmail.setSSL(isSSL());
260 LOG.info("(isSSL()={})", isSSL());
261 oMultiPartEmail.setTLS(isTLS());
262 LOG.info("(isTLS()={})", isTLS());
263
264 oSession = oMultiPartEmail.getMailSession();
265 MimeMessage oMimeMessage = new MimeMessage(oSession);
266
267 LOG.info("oMimeMessage oSession: " + oSession);
268
269 //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
270 oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
271 //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
272
273 LOG.info("oMimeMessage From: " + getFrom());
274
275 String sReceiverName = "receiver";
276 if (asTo.length == 1) {
277 sReceiverName = getToName();
278 }
279 for (String s : asTo) {
280 LOG.info("oMimeMessage.addRecipient (s={})", s);
281 //oMultiPartEmail.addTo(s, "receiver");
282 oMimeMessage.addRecipient(Message.RecipientType.TO,
283 new InternetAddress(s, sReceiverName, DEFAULT_ENCODING));
284 }
285
286 //oMimeMessage.addRecipient(Message.RecipientType.TO,
287 // new InternetAddress(sTo, "recipient", DEFAULT_ENCODING));
288 //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));
289 oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);
290 LOG.info("oMimeMessage head: " + getHead());
291
292 _AttachBody(getBody());
293 LOG.info("(getBody()={})", getBody());
294 oMimeMessage.setContent(oMultiparts);
295 LOG.info("oMimeMessage content: " + oMimeMessage.getContent().toString());
296 // oMimeMessage.getRecipients(Message.RecipientType.CC);
297 //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage});
298
299 try{
300
301 Transport.send(oMimeMessage);
302 }
303 catch(Exception ex){
304 LOG.info("There are some eroor during mail transport: " + ex);
305 }
306
307 LOG.info("Mail was transported....");
308 LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!");
309 } catch (Exception oException) {
310 LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo());
311 LOG.trace("FAIL:", oException);
312 throw new EmailException("Error happened when sending email (" + getTo() + ")"
313 + "Exception message: " + oException.getMessage(), oException);
314 }
315 LOG.info("SUCCESS: Sent!");
316 LOG.info("sendOld ended...");
317}
318
319public Mail _AttachBody(String sBody) {
320 try {
321 MimeBodyPart oMimeBodyPart = new MimeBodyPart();
322 //oMimeBodyPart.setText(sBody,DEFAULT_ENCODING,"Content-Type: text/html;");
323 oMimeBodyPart.setText(sBody, DEFAULT_ENCODING);
324 // oMimeBodyPart.setHeader("Content-Type", "text/html");
325 oMimeBodyPart.setHeader("Content-Type", "text/html;charset=utf-8");
326 oMultiparts.addBodyPart(oMimeBodyPart);
327 LOG.info("sBodylength()={}", sBody != null ? sBody.length() : "null");
328 } catch (Exception oException) {
329 LOG.error("FAIL:", oException);
330 }
331 return this;
332}
333
334public Mail _Attach(File oFile) {
335 _Attach(new FileDataSource(oFile), oFile.getName(), "");
336 return this;
337}
338
339public Mail _Attach(File[] aFile) {
340 LOG.info("(aFile.length={})", aFile.length);
341 for (File oFile : aFile) {
342 _Attach(oFile);
343 }
344 return this;
345}
346
347public Mail _Attach(DataSource oDataSource, String sFileName, String sDescription) {
348 LOG.info("_Attach started..");
349 try {
350 MimeBodyPart oMimeBodyPart = new MimeBodyPart();
351 oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
352 oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
353 oMimeBodyPart.setFileName(MimeUtility.encodeText(sFileName));
354 oMultiparts.addBodyPart(oMimeBodyPart);
355 LOG.info("(sFileName={}, sDescription={})", sFileName, sDescription);
356 } catch (Exception oException) {
357 LOG.error("FAIL: {} (sFileName={},sDescription={})", oException.getMessage(), sFileName, sDescription);
358 LOG.trace("FAIL:", oException);
359 }
360 LOG.info("_Attach ended..");
361 return this;
362}
363
364public Mail _Attach(URL[] aoURL) {
365 return _Attach(aoURL, null);
366}
367
368public Mail _Attach(URL[] aoURL, String[] asName) {
369 LOG.info("(asName={})", asName);
370 for (int n = 0; n < aoURL.length; n++) {
371 try {
372 if (asName == null) {
373 _Attach(aoURL[n], null);
374 } else {
375 _Attach(aoURL[n], asName[n]);
376 }
377 } catch (Exception oException) {
378 LOG.error("FAIL:", oException);
379 }
380 }
381 return this;
382}
383
384public Mail _Attach(URL oURL, String sName) {
385 try {
386 MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
387 oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
388 DataSource oDataSource = new URLDataSource(oURL);
389 oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
390 //oPart.setFileName(MimeUtility.encodeText(source.getName()));
391 oMimeBodyPart.setFileName(
392 MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
393 oMultiparts.addBodyPart(oMimeBodyPart);
394 LOG.info("(sName={})", sName);
395 } catch (Exception oException) {
396 LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
397 LOG.trace("FAIL:", oException);
398 }
399 return this;
400}
401
402public static String sMailOnly(String sMail) {
403 String sMailNew = sMail;
404 try {
405 if (sMailNew.contains("<")) {
406 String[] asMail = sMailNew.split("\<");
407 sMailNew = asMail[1];
408 asMail = sMailNew.split("\>");
409 sMailNew = asMail[0];
410 }
411 } catch (Exception oException) {
412 LOG.warn("FAIL: {} (sMail={},sMailNew={})", oException.getMessage(), sMail, sMailNew);
413 }
414 return sMailNew;
415}
416
417//public void sendWithUniSender() throws EmailException {
418public boolean sendWithUniSender() {
419 LOG.info("Init...");
420 boolean result = true;
421 Object oID_Message = null;
422 StringBuilder sbBody = new StringBuilder();
423 try {
424 sbBody.append("host: ");
425 sbBody.append(getHost());
426 sbBody.append(":");
427 sbBody.append(getPort());
428 sbBody.append("nAuthUser:");
429 sbBody.append(getAuthUser());
430 sbBody.append("nfrom:");
431 sbBody.append(getFrom());
432 sbBody.append("nto:");
433 sbBody.append(getTo());
434 sbBody.append("nhead:");
435 sbBody.append(getHead());
436
437 String sKey_Sender = generalConfig.getKey_UniSender_Mail();
438 long nID_Sender = generalConfig.getSendListId_UniSender_Mail();
439 if (StringUtils.isBlank(sKey_Sender)) {
440 throw new IllegalArgumentException("Please check api_key in UniSender property file configuration");
441 }
442
443 LOG.info("oUniSender - {}", oUniSender);
444 LOG.info("methodCallRunner - {}", methodCallRunner);
445 oUniSender.setMethodCallRunner(methodCallRunner);
446
447 if (getTo().contains(",")) {
448 String[] asMail = getTo().split("\,");
449 for (String sMail : asMail) {
450 sMail = sMailOnly(sMail);
451 UniResponse oUniResponse_Subscribe = oUniSender
452 .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
453 LOG.info("(sMail={},oUniResponse_Subscribe={})", sMail, oUniResponse_Subscribe);
454 }
455 } else {
456 String sMail = sMailOnly(getTo());
457 UniResponse oUniResponse_Subscribe = oUniSender
458 .subscribe(Collections.singletonList(String.valueOf(nID_Sender)), sMail, getToName());
459 LOG.info("(oUniResponse_Subscribe={})", oUniResponse_Subscribe);
460 }
461
462 String sBody = getBody();
463 //sBody = sBody + "" + "<br>Ð”Ð»Ñ Ð¾Ñ‚Ð¿Ð¸Ñки перейдите по <a href="{{UnsubscribeUrl}}">ÑÑылке</a>";
464 sBody = sBody + "" + "<br>Якщо Ви бажаєте відмовитиÑÑ Ð²Ñ–Ð´ повідомлень, будь лаÑка, натиÑніть <a href="{{UnsubscribeUrl}}"тут</a>/";
465
466 CreateEmailMessageRequest.Builder oBuilder = CreateEmailMessageRequest
467 //.getBuilder(sKey_Sender, "en")
468 .getBuilder(sKey_Sender, "ua")
469 .setSenderName("no reply")
470 .setSenderEmail(getFrom())
471 .setSubject(getHead())
472 .setBody(sBody)
473 .setListId(String.valueOf(nID_Sender));
474
475 try {
476 int nAttachments = oMultiparts.getCount();
477 for (int i = 0; i < nAttachments; i++) {
478 BodyPart oBodyPart = oMultiparts.getBodyPart(i);
479 String sFileName = oBodyPart.getFileName();
480 InputStream oInputStream = oBodyPart.getInputStream();
481 oBuilder.setAttachment(sFileName, oInputStream);
482 }
483 } catch (IOException e) {
484 throw new Exception("Error while getting attachment.", e);
485 } catch (MessagingException e) {
486 throw new Exception("Error while getting attachment.", e);
487 }
488
489 CreateEmailMessageRequest oCreateEmailMessageRequest = oBuilder.build();
490
491 UniResponse oUniResponse_CreateEmailMessage = oUniSender.createEmailMessage(oCreateEmailMessageRequest);
492 LOG.info("(oUniResponse_CreateEmailMessage={})", oUniResponse_CreateEmailMessage);
493
494 if (oUniResponse_CreateEmailMessage != null && oUniResponse_CreateEmailMessage.getResult() != null) {
495 Map<String, Object> mParam = oUniResponse_CreateEmailMessage.getResult();
496 LOG.info("(mParam={})", mParam);
497 oID_Message = mParam.get("message_id");
498 if (oID_Message != null) {
499 LOG.info("(oID_Message={})", oID_Message);
500 CreateCampaignRequest oCreateCampaignRequest = CreateCampaignRequest.getBuilder(sKey_Sender, "en")
501 .setMessageId(oID_Message.toString())
502 .build();
503
504 UniResponse oUniResponse_CreateCampaign = oUniSender
505 .createCampaign(oCreateCampaignRequest, getTo());
506 LOG.info("(oUniResponse_CreateCampaign={})", oUniResponse_CreateCampaign);
507 } else {
508 result = false;
509 LOG.error("error while email creation " + oUniResponse_CreateEmailMessage.getError());
510 //throw new EmailException("error while email creation " + oUniResponse_CreateEmailMessage.getError());
511 }
512 }
513 } catch (Exception oException) {
514 result = false;
515 LOG.error("FAIL: {} (oID_Message()={},getTo()={})", oException.getMessage(), oID_Message, getTo());
516 new Log(oException, LOG)
517 ._Case("Mail_FailUS")
518 ._Status(Log.LogStatus.ERROR)
519 ._Head("First try send fail")
520 ._Param("getTo", getTo())
521 ._Param("sbBody", sbBody)
522 ._Param("oID_Message", oID_Message)
523 .save()
524 ;
525 }
526 LOG.info("SUCCESS: sent!");
527 return result;
528}
529
530private void sendAlternativeWay(String sbBody) {
531 LOG.info("sendAlternativeWay started...");
532 try {
533 sendOld();
534 } catch (Exception oException1) {
535 new Log(oException1, LOG)//this.getClass()
536 ._Case("Mail_FailAlter")
537 ._Status(Log.LogStatus.ERROR)
538 ._Head("Final send trying fail")
539 //._Body(oException1.getMessage())
540 ._Param("getTo", getTo())
541 ._Param("sbBody", sbBody)
542 .save()
543 ;
544 }
545 LOG.info("sendAlternativeWay ended...");
546}
547
548}
549
550SomeController {
551
552@Autowired
553Mail mail;
554
555sendTo() {
556 mail.setTo("Some address");
557 mail.set....
558 mail.set....
559 mail.set....
560 mail.send();
561 }
562}