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 package info.magnolia.module.mail.handlers;
35
36 import info.magnolia.module.mail.templates.MgnlEmail;
37
38 import java.util.ArrayList;
39 import java.util.Arrays;
40
41 import javax.mail.Transport;
42
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46
47
48
49
50
51
52 public class ThreadedMailHandler implements MgnlMailHandler {
53
54 Logger log = LoggerFactory.getLogger(ThreadedMailHandler.class);
55
56 ArrayList<MgnlEmail> emails = new ArrayList<MgnlEmail>();
57
58 MailThread thread;
59
60 private ThreadedMailHandler() {
61 this.thread = new MailThread();
62 Thread bb = new Thread(this.thread);
63 bb.start();
64 }
65
66 @Override
67 protected void finalize() throws Throwable {
68 this.thread.setStop(true);
69 super.finalize();
70 }
71
72
73
74
75
76
77 @Override
78 public void prepareAndSendMail(MgnlEmail email) throws Exception {
79 email.setBodyNotSetFlag(true);
80 synchronized (this) {
81 this.emails.add(email);
82 }
83 this.thread.notify();
84 }
85
86
87
88
89
90
91 @Override
92 public void sendMail(MgnlEmail email) throws Exception {
93 synchronized (this) {
94 this.emails.add(email);
95 }
96 this.thread.notify();
97 }
98
99
100
101
102 class MailThread implements Runnable {
103
104 boolean stop = false;
105
106 @Override
107 public void run() {
108 while (!this.stop) {
109 if (ThreadedMailHandler.this.emails.size() == 0) {
110 synchronized (this) {
111 try {
112 wait();
113 }
114 catch (InterruptedException e) {
115 ThreadedMailHandler.this.log.info("Mail Thread was interrupted");
116 }
117 }
118 }
119 else {
120 MgnlEmail email = null;
121 synchronized (this) {
122 if (ThreadedMailHandler.this.emails.size() > 0) {
123 email = ThreadedMailHandler.this.emails.remove(0);
124 }
125 }
126 if (email != null) {
127 try {
128 if (email.isBodyNotSetFlag()) {
129
130 }
131 try {
132 Transport.send(email);
133 ThreadedMailHandler.this.log.info("Mail has been sent to: ["
134 + Arrays.asList(email.getAllRecipients())
135 + "]");
136 }
137 catch (Exception e) {
138 ThreadedMailHandler.this.log.error("Email to: ["
139 + Arrays.asList(email.getAllRecipients())
140 + "] was not sent because of an error", e);
141 }
142 }
143 catch (Exception e) {
144 e.printStackTrace();
145 }
146 }
147 }
148
149 }
150 }
151
152 public boolean isStop() {
153 return this.stop;
154 }
155
156 public void setStop(boolean stop) {
157 this.stop = stop;
158 this.notify();
159 }
160 }
161 }