]> git.mxchange.org Git - jmailer-ee.git/blob - src/org/mxchange/jmailee/model/delivery/BaseMailerBean.java
Rewrite:
[jmailer-ee.git] / src / org / mxchange / jmailee / model / delivery / BaseMailerBean.java
1 /*
2  * Copyright (C) 2016, 2017 Roland Häder
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.jmailee.model.delivery;
18
19 import java.io.StringWriter;
20 import java.text.MessageFormat;
21 import java.util.Date;
22 import java.util.Properties;
23 import javax.mail.MessagingException;
24 import javax.mail.Session;
25 import javax.mail.Transport;
26 import javax.mail.internet.InternetAddress;
27 import javax.mail.internet.MimeMessage;
28 import javax.naming.Context;
29 import javax.naming.InitialContext;
30 import javax.naming.NamingException;
31 import org.apache.velocity.Template;
32 import org.apache.velocity.VelocityContext;
33 import org.apache.velocity.app.VelocityEngine;
34 import org.apache.velocity.runtime.RuntimeConstants;
35 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
36 import org.mxchange.jcoreeelogger.beans.local.logger.Log;
37 import org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal;
38 import org.mxchange.jmailee.model.delivery.wrapper.WrapableEmailDelivery;
39
40 /**
41  * A general email bean for sending out mails from templates
42  * <p>
43  * @author Roland Häder<roland@mxchange.org>
44  */
45 public abstract class BaseMailerBean implements DeliverableEmailLocal {
46
47         /**
48          * Serial number
49          */
50         private static final long serialVersionUID = 14_598_912_753_106L;
51
52         /**
53          * Logger bean
54          */
55         @Log
56         private LoggerBeanLocal loggerBeanLocal;
57
58         /**
59          * Properties for this mailer
60          * <p>
61          * Valid are: - mailer.errorsto = Email address for "Errors-To" header -
62          * mailer.bouncesto = Email address for "Bounces-To" header (optional, if
63          * not set, errorsto must be set) - mailer.xloop = Email address for
64          * "X-Loop" header (optional, if not set, errorsto must be set)
65          */
66         private Properties properties;
67
68         /**
69          * Template engine
70          */
71         private final VelocityEngine templateEngine;
72
73         /**
74          * Default constructor
75          */
76         protected BaseMailerBean () {
77                 try {
78                         // Get initial context
79                         Context context = new InitialContext();
80
81                         // Lookup logger
82                         this.loggerBeanLocal = (LoggerBeanLocal) context.lookup("java:global/jcore-logger-ejb/logger!org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal"); //NOI18N
83                 } catch (final NamingException ex) {
84                         // Continue to throw
85                         throw new RuntimeException(MessageFormat.format("context.lookup() failed: {0}", ex.getMessage()), ex); //NOI18N
86                 }
87
88                 // Init template engine
89                 this.templateEngine = new VelocityEngine();
90                 this.templateEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); //NOI18N
91                 this.templateEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); //NOI18N
92                 this.templateEngine.init();
93         }
94
95         /**
96          * Sends an email to given email address with subject line.
97          * <p>
98          * @param emailAddress Email address for recipient
99          * @param subjectLine  Subject line
100          * @param writer       Body part
101          * @param mailSession  Corresponding mail session to use
102          * <p>
103          * @throws MessagingException If something happened on message delivery
104          */
105         private void deliverMail (final WrapableEmailDelivery emailWrapper, final StringWriter writer, final Session mailSession) throws MessagingException {
106                 // Trace message
107                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("sendMail: emailWrapper={0},body={1},mailSession={2} - CALLED!", emailWrapper, writer, mailSession)); //NOI18N
108
109                 // Are the additional properties and all parameter set?
110                 if (null == this.properties) {
111                         // Nothing set
112                         throw new NullPointerException("this.properties is null"); //NOI18N
113                 } else if (null == emailWrapper) {
114                         // Throw NPE
115                         throw new NullPointerException("emailWrapper is null"); //NOI18N
116                 } else if (emailWrapper.getLocale() == null) {
117                         // Throw it again
118                         throw new NullPointerException("emailWrapper.locale is null"); //NOI18N
119                 } else if (emailWrapper.getRecipientAddress() == null) {
120                         // Throw it again
121                         throw new NullPointerException("emailWrapper.recipient is null"); //NOI18N
122                 } else if (emailWrapper.getTemplateName() == null) {
123                         // Throw it again
124                         throw new NullPointerException("emailWrapper.templateName is null"); //NOI18N
125                 } else if (emailWrapper.getTemplateName().isEmpty()) {
126                         // Throw IAE
127                         throw new IllegalArgumentException("emailWrapper.templateName is empty"); //NOI18N
128                 } else if (emailWrapper.getTemplateVariables() == null) {
129                         // Throw NPE again
130                         throw new NullPointerException("emailWrapper.templateVariables is null"); //NOI18N
131                 } else if (emailWrapper.getTemplateVariables().isEmpty()) {
132                         // Throw IAE
133                         throw new IllegalArgumentException("emailWrapper.templateVariables is empty"); //NOI18N
134                 } else if (!emailWrapper.getTemplateVariables().containsKey("baseUrl")) { //NOI18N
135                         // Not set
136                         throw new IllegalArgumentException("emailWrapper.templateVariables.baseUrl is not set"); //NOI18N
137                 } else if (null == writer) {
138                         // Throw NPE
139                         throw new NullPointerException("writer is null"); //NOI18N
140                 } else if (writer.toString().isEmpty()) {
141                         // Throw IAE
142                         throw new IllegalArgumentException("writer.string is empty"); //NOI18N
143                 } else if (null == mailSession) {
144                         // Throw NPE
145                         throw new NullPointerException("mailSession is null"); //NOI18N
146                 }
147
148                 // Get MIME message instance
149                 MimeMessage message = new MimeMessage(mailSession);
150
151                 // Set subject, recipients and body
152                 message.setSubject(emailWrapper.getSubjectLine());
153                 message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailWrapper.getRecipientAddress().toString(), true));
154                 message.setSentDate(new Date());
155                 message.setText(writer.toString());
156                 message.setHeader("MIME-Version", "1.0"); //NOI18N
157                 message.setHeader("Content-Type", "text/plain; charset=UTF-8"); //NOI18N
158                 message.setHeader("Content-Transfer-Encoding", "8bit"); //NOI18N
159
160                 // Is property "errorsto" set ?
161                 if ((this.properties.containsKey("mailer.errorsto")) && (!this.properties.getProperty("mailer.errorsto").isEmpty())) { //NOI18N
162                         // Use this
163                         message.setHeader("Errors-To", this.properties.getProperty("mailer.errorsto")); //NOI18N#
164                 }
165
166                 // Is the property "bouncesto" set?
167                 if ((this.properties.containsKey("mailer.bouncesto")) && (!this.properties.getProperty("mailer.bouncesto").isEmpty())) { //NOI18N
168                         // Use this
169                         message.setHeader("Bounces-To", this.properties.getProperty("mailer.bouncesto")); //NOI18N
170                 }
171
172                 // Is the property "xloop" set?
173                 if ((this.properties.containsKey("mailer.xloop")) && (!this.properties.getProperty("mailer.xloop").isEmpty())) { //NOI18N
174                         // Use this
175                         message.setHeader("X-Loop", this.properties.getProperty("mailer.xloop")); //NOI18N
176                 }
177
178                 // Directly send email
179                 Transport.send(message);
180
181                 // Trace message
182                 this.getLoggerBeanLocal().logTrace("init: EXIT!"); //NOI18N
183         }
184
185         /**
186          * Sends given mail template to all addresses found in email wrapper
187          * <p>
188          * @param template     Template to send
189          * @param context      Velocity context
190          * @param emailWrapper Email wrapper containing recipient and such
191          * @param mailSession  Mail session
192          * <p>
193          * @throws MessagingException If something happened on message delivery
194          */
195         protected void deliverMailWithTemplate (final Template template, final VelocityContext context, final WrapableEmailDelivery emailWrapper, final Session mailSession) throws MessagingException {
196                 // Log trace message
197                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("sendMailTemplate: template={0},emailWrapper={1},mailSession={2} - CALLED!", template, emailWrapper, mailSession)); //NOI18N
198
199                 // The parameters must be valid
200                 if (null == template) {
201                         // Throw NPE
202                         throw new NullPointerException("template is null"); //NOI18N
203                 } else if (null == emailWrapper) {
204                         // Throw NPE
205                         throw new NullPointerException("emailWrapper is null"); //NOI18N
206                 } else if (emailWrapper.getLocale() == null) {
207                         // Throw it again
208                         throw new NullPointerException("emailWrapper.locale is null"); //NOI18N
209                 } else if (emailWrapper.getRecipientAddress() == null) {
210                         // Throw it again
211                         throw new NullPointerException("emailWrapper.recipient is null"); //NOI18N
212                 } else if (emailWrapper.getTemplateName() == null) {
213                         // Throw it again
214                         throw new NullPointerException("emailWrapper.templateName is null"); //NOI18N
215                 } else if (emailWrapper.getTemplateName().isEmpty()) {
216                         // Throw IAE
217                         throw new IllegalArgumentException("emailWrapper.templateName is empty"); //NOI18N
218                 } else if (emailWrapper.getTemplateVariables() == null) {
219                         // Throw NPE again
220                         throw new NullPointerException("emailWrapper.templateVariables is null"); //NOI18N
221                 } else if (emailWrapper.getTemplateVariables().isEmpty()) {
222                         // Throw IAE
223                         throw new IllegalArgumentException("emailWrapper.templateVariables is empty"); //NOI18N
224                 } else if (!emailWrapper.getTemplateVariables().containsKey("baseUrl")) { //NOI18N
225                         // Not set
226                         throw new IllegalArgumentException("emailWrapper.templateVariables.baseUrl is not set"); //NOI18N
227                 } else if (null == mailSession) {
228                         // Throw NPE
229                         throw new NullPointerException("mailSession is null"); //NOI18N
230                 }
231
232                 // Get writer instance
233                 StringWriter writer = new StringWriter();
234
235                 // Merge template
236                 template.merge(context, writer);
237
238                 // Get all out and send it
239                 this.deliverMail(emailWrapper, writer, mailSession);
240
241                 // Trace message
242                 this.getLoggerBeanLocal().logTrace("init: EXIT!"); //NOI18N
243         }
244
245         /**
246          * Getter for logger bean
247          * <p>
248          * @return Local logger bean
249          */
250         protected LoggerBeanLocal getLoggerBeanLocal () {
251                 return this.loggerBeanLocal;
252         }
253
254         /**
255          * Setter for initial properties
256          * <p>
257          * @param properties Initial properties
258          */
259         @SuppressWarnings ("AssignmentToCollectionOrArrayFieldFromParameter")
260         protected void setProperties (final Properties properties) {
261                 // Trace message
262                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("setProperties: properties={0} - CALLED!", properties)); //NOI18N
263
264                 // Are all required properties set?
265                 if (null == properties) {
266                         // Is null
267                         throw new NullPointerException("properties is null"); //NOI18N
268                 } else if (!properties.containsKey("mailer.errorsto")) { //NOI18N
269                         // Errors-To not set
270                         throw new IllegalArgumentException("properties.mailer.errorsto is not set"); //NOI18N
271                 } else if (!properties.containsKey("mailer.bouncesto")) { //NOI18N
272                         // Errors-To not set
273                         throw new IllegalArgumentException("properties.mailer.bouncesto is not set"); //NOI18N
274                 }
275
276                 // Set it here
277                 this.properties = properties;
278
279                 // Trace message
280                 this.getLoggerBeanLocal().logTrace("setProperties: EXIT!"); //NOI18N
281         }
282
283         /**
284          * Getter for template engine instance
285          * <p>
286          * @return Template engine instance
287          */
288         protected VelocityEngine getTemplateEngine () {
289                 return this.templateEngine;
290         }
291
292 }