1 64 65 70 package com.jcorporate.expresso.core.misc; 71 72 import com.jcorporate.expresso.core.db.DBException; 73 import com.jcorporate.expresso.services.dbobj.Setup; 74 import org.apache.log4j.Logger; 75 76 import javax.activation.DataHandler ; 77 import javax.activation.FileDataSource ; 78 import javax.mail.Message ; 79 import javax.mail.Session ; 80 import javax.mail.Transport ; 81 import javax.mail.internet.AddressException ; 82 import javax.mail.internet.InternetAddress ; 83 import javax.mail.internet.MimeBodyPart ; 84 import javax.mail.internet.MimeMessage ; 85 import javax.mail.internet.MimeMultipart ; 86 import java.util.ArrayList ; 87 import java.util.Date ; 88 import java.util.Iterator ; 89 import java.util.List ; 90 import java.util.Properties ; 91 import java.util.Vector ; 92 93 106 public class EMailSender { 107 private static final String thisClass = EMailSender.class.getName(); 108 private static transient final Logger log = Logger.getLogger(EMailSender.class); 109 110 protected String to = null; 111 protected String from = null; 112 protected String personal = null; 113 protected String host = null; 114 protected String user = null; 115 protected String password = null; 116 protected String subject = null; 117 protected String text = null; 118 protected String dbName = null; 119 protected List attachments = null; 120 protected List dataSourceAttachments = null; 121 122 protected boolean htmlFormat = false; 124 private int maxConnectRetries = 0; 125 126 private long connectRetryDelay = 10000; 128 131 public EMailSender() { 132 super(); 133 } 134 135 138 private String messageDetails() { 139 int aCount = 0; 140 int dsACount = 0; 141 142 if (attachments != null) { 143 aCount = attachments.size(); 144 } 145 if (attachments != null) { 146 dsACount = dataSourceAttachments.size(); 147 } 148 149 return ("Message Details:\n" + "To '" + 150 StringUtil.notNull(to) + "'\n" + "From '" + 151 StringUtil.notNull(from) + "'\n" + "Via host '" + 152 StringUtil.notNull(host) + "'\n" + "User '" + 153 StringUtil.notNull(user) + "'\n" + "Subject '" + 154 StringUtil.notNull(subject) + "'\n" + "Message '" + 155 StringUtil.notNull(text) + "'\n" + "Db/Context '" + 156 StringUtil.notNull(dbName) + "'\n" + "With " + aCount + 157 " file attachments and " + dsACount + " data source attachments."); 158 } 159 160 167 public void addFileAttachment(String name) { 168 169 if (attachments == null) { 171 attachments = new ArrayList (4); 172 } 173 174 attachments.add(name); 176 } 177 178 183 public void addFileAttachments(Vector fileNames) { 184 185 if (attachments == null) { 187 attachments = new ArrayList (4); 188 } 189 for (Iterator itor = fileNames.iterator(); itor.hasNext();) { 191 attachments.add(itor.next()); 192 } 193 } 194 195 196 203 public void addDataSourceAttachment(ByteArrayDataSource dataSource) { 204 205 if (dataSourceAttachments == null) { 207 dataSourceAttachments = new ArrayList (4); 208 } 209 210 dataSourceAttachments.add(dataSource); 212 } 213 214 222 public void addDataSourceAttachments(List dataSourceList) { 223 224 if (attachments == null) { 226 attachments = new ArrayList (4); 227 } 228 229 for (Iterator itor = dataSourceList.iterator(); itor.hasNext();) { 231 ByteArrayDataSource dataSource = (ByteArrayDataSource) itor.next(); 232 dataSourceAttachments.add(dataSource); 233 } 234 } 235 236 242 public String getDBName() { 243 String db = dbName; 244 245 if ((db == null) || (db.trim().equals(""))) { 246 db = "default"; 247 } 248 249 dbName = db; 250 251 return db; 252 } 253 254 262 private String getFromAddress() 263 throws Exception { 264 String addr = from; 265 266 try { 267 if (addr == null) { 268 addr = Setup.getValueRequired(getDBName(), "MAILFrom"); 269 } 270 } catch (DBException dex) { 271 log.error("DB exception getting MAILFrom:" + messageDetails(), dex); 272 throw dex; 273 } 274 275 from = addr; 276 277 return addr; 278 } 279 280 281 289 private String getSMTPHost() 290 throws Exception { 291 String thisMethod = thisClass + "getSMTPHost()"; 292 String myHost = StringUtil.notNull(host); 293 294 try { 295 if (myHost.equals("")) { 296 myHost = Setup.getValueRequired(getDBName(), "MAILServer"); 297 } 298 } catch (DBException dex) { 299 log.error("DB exception getting MAILServer:" + messageDetails(), 300 dex); 301 throw new Exception (thisMethod + 302 ":DB exception getting MAILServer:" + 303 dex.getMessage()); 304 } 305 306 host = myHost; 307 308 return myHost; 309 } 310 311 312 319 private String getSMTPPassword() { 320 String myPassword = password; 321 322 try { 323 if (myPassword == null) { 324 myPassword = Setup.getValueRequired(getDBName(), 325 "MAILPassword"); 326 } 327 } catch (DBException dex) { 328 myPassword = null; 329 } 330 331 password = myPassword; 332 333 return myPassword; 334 } 335 336 343 private String getSMTPUser() { 344 String myUser = StringUtil.notNull(user); 345 346 try { 347 if (myUser.equals("")) { 348 myUser = Setup.getValueRequired(getDBName(), "MAILUserName"); 349 } 350 } catch (DBException dex) { 351 myUser = null; 352 } 353 354 user = myUser; 355 356 return myUser; 357 } 358 359 364 public void send() throws Exception { 365 String myFrom = getFromAddress(); 367 368 String myHost = getSMTPHost(); 370 371 String myUser = getSMTPUser(); 373 374 String myPassword = getSMTPPassword(); 376 377 String myPersonal = getPersonal(); 378 379 boolean useAuth = false; 381 StringUtil.assertNotBlank(myHost, 382 "Host cannot be blank when sending email"); 383 384 if (log.isDebugEnabled()) { 385 log.debug("Sending email:" + messageDetails()); 386 } 387 if (to.indexOf("@") == -1) { 389 log.warn("Invalid to address, does not contain \"@\" - " + to); 390 391 return; 393 } 394 if (myUser != null && !myUser.trim().equals("")) { 397 useAuth = true; 398 } 399 400 Session session = null; 401 Transport trans = null; 402 InternetAddress [] fromAddr = null; 403 InternetAddress [] toAddr = null; 404 405 try { 407 fromAddr = InternetAddress.parse(myFrom, false); 408 } catch (AddressException aex) { 409 log.error("Invalid from address - '" + from + "':" + messageDetails(), aex); 410 throw aex; 411 } 412 try { 414 toAddr = InternetAddress.parse(to, false); 415 } catch (AddressException aex) { 416 log.error("Invalid to address - '" + to + "':" + messageDetails(), aex); 417 throw aex; 418 } 419 420 Properties props = new Properties (); 425 props.put("mail.smtp.host", myHost); 427 try { 428 if (useAuth) { 429 430 if (log.isDebugEnabled()) { 432 log.debug("Setting up secure email session, host=" + 433 myHost + " user=" + myUser); 434 } 435 436 props.put("mail.smtp.auth", "true"); 437 438 EMailAuthenticator auth = new EMailAuthenticator(); 439 440 auth.setUser(myUser); 443 auth.setPassword(myPassword); 444 445 session = Session.getInstance(props, auth); 447 } else { 448 449 if (log.isDebugEnabled()) { 451 log.debug("Setting up normal email session, host=" + 452 myHost); 453 } 454 455 session = Session.getInstance(props, null); 456 } 457 if (ConfigManager.getContext(getDBName()).mailDebug()) { 460 session.setDebug(true); 461 } 462 } catch (Exception e) { 463 log.error("Unable to create mail session:" + messageDetails(), e); 464 throw e; 465 } 466 467 MimeMessage msg = null; 472 473 try { 474 475 msg = new MimeMessage (session); 477 478 fromAddr[0].setPersonal(myPersonal); 480 msg.setFrom(fromAddr[0]); msg.setRecipients(Message.RecipientType.TO, toAddr); msg.setSubject(subject); msg.setSentDate(new Date ()); 486 MimeMultipart mp = new MimeMultipart (); 489 490 MimeBodyPart mbp = new MimeBodyPart (); 493 mbp.setText(text); 494 if (htmlFormat) { 495 mbp.setContent(text, "text/html"); } 497 498 mp.addBodyPart(mbp); 499 500 String oneFileName = null; 504 505 if (attachments != null) { 506 for (Iterator itor = attachments.iterator(); itor.hasNext();) { 511 oneFileName = (String ) itor.next(); 512 513 MimeBodyPart mbp2 = new MimeBodyPart (); 514 FileDataSource fds = new FileDataSource (oneFileName); 515 mbp2.setDataHandler(new DataHandler (fds)); 516 mbp2.setFileName(fds.getName()); 517 mp.addBodyPart(mbp2); 518 } 519 } 520 521 if (dataSourceAttachments != null) { 522 for (Iterator itor = dataSourceAttachments.iterator(); itor.hasNext();) { 526 ByteArrayDataSource bads = (ByteArrayDataSource) itor.next(); 527 528 MimeBodyPart mbp3 = new MimeBodyPart (); 529 mbp3.setDataHandler(new DataHandler (bads)); 530 mbp3.setFileName(bads.getName()); 531 mp.addBodyPart(mbp3); 532 } 533 } 534 535 msg.setContent(mp); 537 } catch (Exception e) { 538 log.error("Error in creating MIME message:" + messageDetails(), e); 539 throw e; 540 } 541 try { 545 546 trans = session.getTransport(toAddr[0]); 548 549 int connectRetries = 0; 551 do { try { 553 trans.connect(); 554 } catch (Exception e) { 555 if (e.getMessage().equals("already connected")) { 556 break; 557 } 558 if (connectRetries >= maxConnectRetries) { 559 throw e; 560 } else { 561 log.debug("Retry (wait=" 562 + connectRetryDelay 563 + "ms) on SMTP connect, count=" 564 + connectRetries 565 + ", error=" 566 + e.getMessage() 567 + ", detail=" 568 + messageDetails()); 569 Thread.sleep(connectRetryDelay); 570 } 571 } 572 } while (connectRetries++ < maxConnectRetries); 573 574 575 576 trans.sendMessage(msg, toAddr); 578 579 trans.close(); 581 } catch (Exception e) { 582 log.error("Error sending email:" + messageDetails(), e); 583 throw e; 584 } 585 } 586 587 588 596 public void send(String to, String subject, String text) 597 throws Exception { 598 setToAddress(to); 599 setSubject(subject); 600 setText(text); 601 send(); 602 } 603 604 605 610 public void setDBName(String newDBName) { 611 dbName = StringUtil.notNull(newDBName); 612 613 if (dbName.equals("")) { 614 dbName = "default"; 615 } 616 } 617 618 623 public void setFromAddress(String from) { 624 this.from = from; 625 } 626 627 628 631 public void setEmailHtmlFormat() { 632 htmlFormat = true; 634 } 635 636 641 public void setPersonal(String personal) { 642 this.personal = personal; 643 } 644 645 650 public String getPersonal() { 651 if (personal == null) { 652 return new String (""); 653 } else { 654 return this.personal; 655 } 656 } 657 658 659 664 public void setSMTPHost(String host) { 665 this.host = host; 666 } 667 668 673 public void setSMTPPassword(String password) { 674 this.password = password; 675 } 676 677 682 public void setSMTPUser(String user) { 683 this.user = user; 684 } 685 686 691 public void setSubject(String subject) { 692 this.subject = subject; 693 } 694 695 700 public void setText(String text) { 701 this.text = text; 702 } 703 704 709 public void setToAddress(String to) { 710 this.to = to; 711 } 712 713 718 public void setConnectRetryDelay(long connectRetryDelay) { 719 this.connectRetryDelay = connectRetryDelay; 720 } 721 722 727 public void setMaxConnectRetries(int maxConnectRetries) { 728 this.maxConnectRetries = maxConnectRetries; 729 } 730 731 } 732 | Popular Tags |