]> git.mxchange.org Git - jmailer-ee.git/blob - src/org/mxchange/jmailee/model/delivery/BaseMailer.java
added method init()
[jmailer-ee.git] / src / org / mxchange / jmailee / model / delivery / BaseMailer.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
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.Address;
24 import javax.mail.MessagingException;
25 import javax.mail.Session;
26 import javax.mail.Transport;
27 import javax.mail.internet.InternetAddress;
28 import javax.mail.internet.MimeMessage;
29 import javax.naming.Context;
30 import javax.naming.InitialContext;
31 import javax.naming.NamingException;
32 import org.apache.velocity.Template;
33 import org.apache.velocity.VelocityContext;
34 import org.apache.velocity.app.VelocityEngine;
35 import org.apache.velocity.runtime.RuntimeConstants;
36 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
37 import org.mxchange.jcoreeelogger.beans.local.logger.Log;
38 import org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal;
39 import org.mxchange.jmailee.model.delivery.wrapper.WrapableEmailDelivery;
40
41 /**
42  * An email class for sending out mails from templates
43  * <p>
44  * @author Roland Haeder<roland@mxchange.org>
45  */
46 public abstract class BaseMailer implements DeliverableEmail {
47
48         /**
49          * Serial number
50          */
51         private static final long serialVersionUID = 14_598_912_753_106L;
52
53         /**
54          * Logger bean
55          */
56         @Log
57         private LoggerBeanLocal loggerBeanLocal;
58
59         /**
60          * Properties for this mailer
61          * <p>
62          * Valid are:
63          * - mailer.errorsto = Email address for "Errors-To" header
64          * - mailer.bouncesto = Email address for "Bounces-To" header (optional, if not set, errorsto must be set)
65          * - mailer.xloop = Email address for "X-Loop" header (optional, if not set, errorsto must be set)
66          */
67         private Properties properties;
68
69         /**
70          * Template engine
71          */
72         private final VelocityEngine templateEngine;
73
74         /**
75          * Default constructor
76          */
77         protected BaseMailer () {
78                 try {
79                         // Get initial context
80                         Context context = new InitialContext();
81
82                         // Lookup logger
83                         this.loggerBeanLocal = (LoggerBeanLocal) context.lookup("java:global/jcore-logger-ejb/logger!org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal"); //NOI18N
84                 } catch (final NamingException ex) {
85                         // Continue to throw
86                         throw new RuntimeException(MessageFormat.format("context.lookup() failed: {0}", ex.getMessage()), ex); //NOI18N
87                 }
88
89                 // Init template engine
90                 this.templateEngine = new VelocityEngine();
91                 this.templateEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); //NOI18N
92                 this.templateEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); //NOI18N
93                 this.templateEngine.init();
94         }
95
96         @Override
97         public VelocityEngine getTemplateEngine () {
98                 return this.templateEngine;
99         }
100
101         @Override
102         public void init (final Properties properties) {
103                 // Trace message
104                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("init: properties={0} - CALLED!", properties)); //NOI18N
105
106                 // Are all required properties set?
107                 if (null == properties) {
108                         // Is null
109                         throw new NullPointerException("properties is null"); //NOI18N
110                 } else if (!properties.containsKey("mailer.errorsto")) { //NOI18N
111                         // Errors-To not set
112                         throw new IllegalArgumentException("properties.mailer.errorsto is not set"); //NOI18N
113                 } else if (!properties.containsKey("mailer.bouncesto")) { //NOI18N
114                         // Errors-To not set
115                         throw new IllegalArgumentException("properties.mailer.bouncesto is not set"); //NOI18N
116                 }
117
118                 // Set it here
119                 this.properties = properties;
120
121                 // Trace message
122                 this.getLoggerBeanLocal().logTrace("init: EXIT!"); //NOI18N
123         }
124
125         /**
126          * Sends an email to given email address with subject line.
127          * <p>
128          * @param emailAddress Email address for recipient
129          * @param subjectLine Subject line
130          * @param body Body part
131          * @param mailSession Corresponding mail session to use
132          * <p>
133          * @throws MessagingException If something happened on message delivery
134          */
135         private void sendMail (final Address emailAddress, final String subjectLine, final String body, final Session mailSession) throws MessagingException {
136                 // Trace message
137                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("sendMail: emailAddress={0},subjectLine={1},body={2},mailSession={3} - CALLED!", emailAddress, subjectLine, body, mailSession)); //NOI18N
138
139                 // Are the additional properties set?
140                 if (null == this.properties) {
141                         // Nothing set
142                         throw new NullPointerException("this.properties is null"); //NOI18N
143                 }
144
145                 // Get MIME message instance
146                 MimeMessage message = new MimeMessage(mailSession);
147
148                 // Set subject, recipients and body
149                 message.setSubject(subjectLine);
150                 message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailAddress.toString(), true));
151                 message.setSentDate(new Date());
152                 message.setText(body);
153                 message.setHeader("MIME-Version", "1.0"); //NOI18N
154                 message.setHeader("Content-Type", "text/plain; charset=UTF-8"); //NOI18N
155                 message.setHeader("Content-Transfer-Encoding", "8bit"); //NOI18N
156                 message.setHeader("Errors-To", this.properties.getProperty("mailer.errorsto")); //NOI18N
157
158                 // Is the property "bouncesto" set?
159                 if (this.properties.containsKey("mailer.bouncesto")) { //NOI18N
160                         // Use this
161                         message.setHeader("Bounces-To", this.properties.getProperty("mailer.bouncesto")); //NOI18N
162                 } else {
163                         // Use "errorsto"
164                         message.setHeader("Bounces-To", this.properties.getProperty("mailer.errorsto")); //NOI18N
165                 }
166
167                 // Is the property "xloop" set?
168                 if (this.properties.containsKey("mailer.xloop")) { //NOI18N
169                         // Use this
170                         message.setHeader("X-Loop", this.properties.getProperty("mailer.xloop")); //NOI18N
171                 } else {
172                         // Use "errorsto"
173                         message.setHeader("X-Loop", this.properties.getProperty("mailer.errorsto")); //NOI18N
174                 }
175
176                 // Directly send email
177                 Transport.send(message);
178         }
179
180         /**
181          * Getter for logger bean
182          * <p>
183          * @return Local logger bean
184          */
185         protected LoggerBeanLocal getLoggerBeanLocal () {
186                 return this.loggerBeanLocal;
187         }
188
189         /**
190          * Sends given mail template to all addresses found in email wrapper
191          * <p>
192          * @param template Template to send
193          * @param context Velocity context
194          * @param emailWrapper Email wrapper containing recipient and such
195          * @param mailSession Mail session
196          * <p>
197          * @throws MessagingException If something happened on message delivery
198          */
199         protected void sendMailTemplate (final Template template, final VelocityContext context, final WrapableEmailDelivery emailWrapper, final Session mailSession) throws MessagingException {
200                 // Log trace message
201                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("sendMailTemplate: template={0},emailWrapper={1},mailSession={2} - CALLED!", template, emailWrapper, mailSession)); //NOI18N
202
203                 // The parameters must be valid
204                 if (null == template) {
205                         // Throw NPE
206                         throw new NullPointerException("template is null"); //NOI18N
207                 } else if (null == emailWrapper) {
208                         // Throw NPE
209                         throw new NullPointerException("emailWrapper is null"); //NOI18N
210                 } else if (emailWrapper.getRecipient() == null) {
211                         // Throw NPE again
212                         throw new NullPointerException("emailWrapper.recipient is null"); //NOI18N
213                 } else if (emailWrapper.getSubjectLine() == null) {
214                         // ... and again
215                         throw new NullPointerException("emailWrapper.subjectLine is null"); //NOI18N
216                 } else if (emailWrapper.getSubjectLine().isEmpty()) {
217                         // Is empty
218                         throw new IllegalArgumentException("emailWrapper.subjectLine is empty"); //NOI18N
219                 } else if (emailWrapper.getTemplateName() == null) {
220                         // ... and again
221                         throw new NullPointerException("emailWrapper.templateName is null"); //NOI18N
222                 } else if (emailWrapper.getTemplateName().isEmpty()) {
223                         // Is empty
224                         throw new IllegalArgumentException("emailWrapper.templateName is empty"); //NOI18N
225                 } else if (emailWrapper.getLocale() == null) {
226                         // Throw NPE again
227                         throw new NullPointerException("emailWrapper.locale is null"); //NOI18N
228                 }
229
230                 // Get writer instance
231                 StringWriter writer = new StringWriter();
232
233                 // Merge template
234                 template.merge(context, writer);
235
236                 // Get all out and send it
237                 this.sendMail(emailWrapper.getRecipient(), emailWrapper.getSubjectLine(), writer.toString(), mailSession);
238         }
239
240 }