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