]> git.mxchange.org Git - jmailer-ee.git/blob - src/org/mxchange/jmailee/model/delivery/BaseMailerBean.java
f859ba8f05a2e2e7ec383e3be2224716eec23ad9
[jmailer-ee.git] / src / org / mxchange / jmailee / model / delivery / BaseMailerBean.java
1 /*
2  * Copyright (C) 2016 - 2022 Free Software Foundation
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.Message;
25 import javax.mail.MessagingException;
26 import javax.mail.Session;
27 import javax.mail.Transport;
28 import javax.mail.internet.InternetAddress;
29 import javax.mail.internet.MimeMessage;
30 import org.apache.velocity.Template;
31 import org.apache.velocity.app.VelocityEngine;
32 import org.apache.velocity.context.Context;
33 import org.apache.velocity.runtime.RuntimeConstants;
34 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
35 import org.mxchange.jcoreee.bean.ejb.BaseEnterpriseBean;
36 import org.mxchange.jmailee.model.delivery.wrapper.WrapableEmailDelivery;
37
38 /**
39  * A general email bean for sending out mails from templates
40  * <p>
41  * @author Roland Häder<roland@mxchange.org>
42  */
43 public abstract class BaseMailerBean extends BaseEnterpriseBean implements DeliverableEmailRemote {
44
45         /**
46          * Serial number
47          */
48         private static final long serialVersionUID = 14_598_912_753_106L;
49
50         /**
51          * Properties for this mailer
52          * <p>
53          * Valid are: - mailer.errorsto = Email address for "Errors-To" header -
54          * mailer.bouncesto = Email address for "Bounces-To" header (optional, if
55          * not set, errorsto must be set) - mailer.xloop = Email address for
56          * "X-Loop" header (optional, if not set, errorsto must be set)
57          */
58         private Properties properties;
59
60         /**
61          * Template engine
62          */
63         private final VelocityEngine templateEngine;
64
65         /**
66          * Default constructor
67          */
68         protected BaseMailerBean () {
69                 // Call super constructor
70                 super();
71
72                 // Init template engine
73                 this.templateEngine = new VelocityEngine();
74                 this.templateEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); //NOI18N
75                 this.templateEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); //NOI18N
76                 this.templateEngine.init();
77         }
78
79         /**
80          * Sends an email to given email address with subject line.
81          * <p>
82          * @param emailAddress Email address for recipient
83          * @param subjectLine  Subject line
84          * @param writer       Body part
85          * @param mailSession  Corresponding mail session to use
86          * <p>
87          * @throws MessagingException If something happened on message delivery
88          */
89         private void deliverMail (final WrapableEmailDelivery emailWrapper, final StringWriter writer, final Session mailSession) throws MessagingException {
90                 // Trace message
91                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("deliverMail: emailWrapper={0},body={1},mailSession={2} - CALLED!", emailWrapper, writer, mailSession)); //NOI18N
92
93                 // Are the additional properties and all parameter set?
94                 if (null == this.properties) {
95                         // Nothing set
96                         throw new NullPointerException("this.properties is null"); //NOI18N
97                 } else if (!this.properties.containsKey("mailer.from")) { //NOI18N
98                         // Throw exception
99                         throw new IllegalStateException("this.properties.mailer.from is not set"); //NOI18N
100                 } else if (null == emailWrapper) {
101                         // Throw NPE
102                         throw new NullPointerException("emailWrapper is null"); //NOI18N
103                 } else if (emailWrapper.getLocale() == null) {
104                         // Throw it again
105                         throw new NullPointerException("emailWrapper.locale is null"); //NOI18N
106                 } else if (emailWrapper.getRecipientAddress() == null) {
107                         // Throw it again
108                         throw new NullPointerException("emailWrapper.recipientAddress is null"); //NOI18N
109                 } else if (emailWrapper.getTemplateName() == null) {
110                         // Throw it again
111                         throw new NullPointerException("emailWrapper.templateName is null"); //NOI18N
112                 } else if (emailWrapper.getTemplateName().isEmpty()) {
113                         // Throw IAE
114                         throw new IllegalArgumentException("emailWrapper.templateName is empty"); //NOI18N
115                 } else if (emailWrapper.getTemplateVariables() == null) {
116                         // Throw NPE again
117                         throw new NullPointerException("emailWrapper.templateVariables is null"); //NOI18N
118                 } else if (emailWrapper.getTemplateVariables().isEmpty()) {
119                         // Throw IAE
120                         throw new IllegalArgumentException("emailWrapper.templateVariables is empty"); //NOI18N
121                 } else if (!emailWrapper.getTemplateVariables().containsKey("baseUrl")) { //NOI18N
122                         // Not set
123                         throw new IllegalArgumentException("emailWrapper.templateVariables.baseUrl is not set"); //NOI18N
124                 } else if (null == writer) {
125                         // Throw NPE
126                         throw new NullPointerException("writer is null"); //NOI18N
127                 } else if (writer.toString().isEmpty()) {
128                         // Throw IAE
129                         throw new IllegalArgumentException("writer.string is empty"); //NOI18N
130                 } else if (null == mailSession) {
131                         // Throw NPE
132                         throw new NullPointerException("mailSession is null"); //NOI18N
133                 }
134
135                 // Parse from address
136                 Address senderAddress = new InternetAddress(this.properties.getProperty("mailer.from"));
137
138                 // Get MIME message instance
139                 MimeMessage message = new MimeMessage(mailSession);
140
141                 // Set subject, recipients and body
142                 message.setFrom(senderAddress);
143                 message.setSubject(emailWrapper.getSubjectLine());
144                 message.setRecipient(Message.RecipientType.TO, emailWrapper.getRecipientAddress());
145                 message.setSentDate(new Date());
146                 message.setText(writer.toString());
147                 message.setHeader("MIME-Version", "1.0"); //NOI18N
148                 message.setHeader("Content-Type", "text/plain; charset=UTF-8"); //NOI18N
149                 message.setHeader("Content-Transfer-Encoding", "8bit"); //NOI18N
150
151                 // Is property "errorsto" set ?
152                 if ((this.properties.containsKey("mailer.errorsto")) && (!this.properties.getProperty("mailer.errorsto").isEmpty())) { //NOI18N
153                         // Use this
154                         message.setHeader("Errors-To", this.properties.getProperty("mailer.errorsto")); //NOI18N#
155                 }
156
157                 // Is the property "bouncesto" set?
158                 if ((this.properties.containsKey("mailer.bouncesto")) && (!this.properties.getProperty("mailer.bouncesto").isEmpty())) { //NOI18N
159                         // Use this
160                         message.setHeader("Bounces-To", this.properties.getProperty("mailer.bouncesto")); //NOI18N
161                 }
162
163                 // Is the property "xloop" set?
164                 if ((this.properties.containsKey("mailer.xloop")) && (!this.properties.getProperty("mailer.xloop").isEmpty())) { //NOI18N
165                         // Use this
166                         message.setHeader("X-Loop", this.properties.getProperty("mailer.xloop")); //NOI18N
167                 }
168
169                 // Directly send email
170                 Transport.send(message);
171
172                 // Trace message
173                 this.getLoggerBeanLocal().logTrace("deliverMail: EXIT!"); //NOI18N
174         }
175
176         /**
177          * Sends given mail template to all addresses found in email wrapper
178          * <p>
179          * @param template     Template to send
180          * @param context      Velocity context
181          * @param emailWrapper Email wrapper containing recipient and such
182          * @param mailSession  Mail session
183          * <p>
184          * @throws MessagingException If something happened on message delivery
185          */
186         protected void deliverMailWithTemplate (final Template template, final Context context, final WrapableEmailDelivery emailWrapper, final Session mailSession) throws MessagingException {
187                 // Log trace message
188                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("deliverMailWithTemplate: template={0},emailWrapper={1},mailSession={2} - CALLED!", template, emailWrapper, mailSession)); //NOI18N
189
190                 // The parameters must be valid
191                 if (null == template) {
192                         // Throw NPE
193                         throw new NullPointerException("template is null"); //NOI18N
194                 } else if (null == emailWrapper) {
195                         // Throw NPE
196                         throw new NullPointerException("emailWrapper is null"); //NOI18N
197                 } else if (emailWrapper.getLocale() == null) {
198                         // Throw it again
199                         throw new NullPointerException("emailWrapper.locale is null"); //NOI18N
200                 } else if (emailWrapper.getRecipientAddress() == null) {
201                         // Throw it again
202                         throw new NullPointerException("emailWrapper.recipientAddress is null"); //NOI18N
203                 } else if (emailWrapper.getTemplateName() == null) {
204                         // Throw it again
205                         throw new NullPointerException("emailWrapper.templateName is null"); //NOI18N
206                 } else if (emailWrapper.getTemplateName().isEmpty()) {
207                         // Throw IAE
208                         throw new IllegalArgumentException("emailWrapper.templateName is empty"); //NOI18N
209                 } else if (emailWrapper.getTemplateVariables() == null) {
210                         // Throw NPE again
211                         throw new NullPointerException("emailWrapper.templateVariables is null"); //NOI18N
212                 } else if (emailWrapper.getTemplateVariables().isEmpty()) {
213                         // Throw IAE
214                         throw new IllegalArgumentException("emailWrapper.templateVariables is empty"); //NOI18N
215                 } else if (!emailWrapper.getTemplateVariables().containsKey("baseUrl")) { //NOI18N
216                         // Not set
217                         throw new IllegalArgumentException("emailWrapper.templateVariables.baseUrl is not set"); //NOI18N
218                 } else if (null == mailSession) {
219                         // Throw NPE
220                         throw new NullPointerException("mailSession is null"); //NOI18N
221                 }
222
223                 // Get writer instance
224                 StringWriter writer = new StringWriter();
225
226                 // Merge template
227                 template.merge(context, writer);
228
229                 // Get all out and send it
230                 this.deliverMail(emailWrapper, writer, mailSession);
231
232                 // Trace message
233                 this.getLoggerBeanLocal().logTrace("deliverMailWithTemplate: EXIT!"); //NOI18N
234         }
235
236         /**
237          * Setter for initial properties
238          * <p>
239          * @param properties Initial properties
240          */
241         @SuppressWarnings ("AssignmentToCollectionOrArrayFieldFromParameter")
242         protected void setProperties (final Properties properties) {
243                 // Trace message
244                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("setProperties: properties={0} - CALLED!", properties)); //NOI18N
245
246                 // Are all required properties set?
247                 if (null == properties) {
248                         // Is null
249                         throw new NullPointerException("properties is null"); //NOI18N
250                 } else if (!properties.containsKey("mailer.from")) { //NOI18N
251                         // From not set
252                         throw new IllegalArgumentException("properties.mailer.from is not set"); //NOI18N
253                 } else if (!properties.containsKey("mailer.errorsto")) { //NOI18N
254                         // Errors-To not set
255                         throw new IllegalArgumentException("properties.mailer.errorsto is not set"); //NOI18N
256                 } else if (!properties.containsKey("mailer.bouncesto")) { //NOI18N
257                         // Bounces-To not set
258                         throw new IllegalArgumentException("properties.mailer.bouncesto is not set"); //NOI18N
259                 }
260
261                 // Set it here
262                 this.properties = properties;
263
264                 // Trace message
265                 this.getLoggerBeanLocal().logTrace("setProperties: EXIT!"); //NOI18N
266         }
267
268         /**
269          * Getter for template engine instance
270          * <p>
271          * @return Template engine instance
272          */
273         protected VelocityEngine getTemplateEngine () {
274                 return this.templateEngine;
275         }
276
277 }