1 package info.magnolia.cms.mail.handlers; 2 3 import info.magnolia.cms.mail.templates.MgnlEmail; 4 5 import java.util.ArrayList ; 6 import java.util.Arrays ; 7 8 import javax.mail.Transport ; 9 10 import org.slf4j.Logger; 11 import org.slf4j.LoggerFactory; 12 13 14 19 public class ThreadedMailHandler implements MgnlMailHandler { 20 21 Logger log = LoggerFactory.getLogger(ThreadedMailHandler.class); 22 23 ArrayList emails = new ArrayList (); 24 25 MailThread thread; 27 private ThreadedMailHandler() { 28 this.thread = new MailThread(); 29 Thread bb = new Thread (this.thread); 30 bb.start(); 31 } 32 33 protected void finalize() throws Throwable { 34 this.thread.setStop(true); 35 super.finalize(); 36 } 37 38 43 public void prepareAndSendMail(MgnlEmail email) throws Exception { 44 email.setBodyNotSetFlag(true); 45 synchronized (this) { 46 this.emails.add(email); 47 } 48 this.thread.notify(); 49 } 50 51 56 public void sendMail(MgnlEmail email) throws Exception { 57 synchronized (this) { 58 this.emails.add(email); 59 } 60 this.thread.notify(); 61 } 62 63 66 class MailThread implements Runnable { 67 68 boolean stop = false; 69 70 public void run() { 71 while (!this.stop) { 72 if (ThreadedMailHandler.this.emails.size() == 0) { synchronized (this) { 74 try { 75 wait(); 76 } 77 catch (InterruptedException e) { 78 ThreadedMailHandler.this.log.info("Mail Thread was interrupted"); 79 } 80 } 81 } 82 else { 83 MgnlEmail email = null; 84 synchronized (this) { 85 if (ThreadedMailHandler.this.emails.size() > 0) { 86 email = (MgnlEmail) ThreadedMailHandler.this.emails.remove(0); 87 } 88 } 89 if (email != null) { 90 try { 91 if (email.isBodyNotSetFlag()) { 92 email.setBody(); 93 } 94 try { 95 Transport.send(email); 96 ThreadedMailHandler.this.log.info("Mail has been sent to: [" 97 + Arrays.asList(email.getAllRecipients()) 98 + "]"); 99 } 100 catch (Exception e) { 101 ThreadedMailHandler.this.log.error("Email to: [" 102 + Arrays.asList(email.getAllRecipients()) 103 + "] was not sent because of an error", e); 104 } 105 } 106 catch (Exception e) { 107 e.printStackTrace(); 108 } 109 } 110 } 111 112 } 113 } 114 115 public boolean isStop() { 116 return this.stop; 117 } 118 119 public void setStop(boolean stop) { 120 this.stop = stop; 121 this.notify(); 122 } 123 } 124 } 125 | Popular Tags |