001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2022 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.mail;
020
021import jakarta.mail.Authenticator;
022import jakarta.mail.Message;
023import jakarta.mail.MessagingException;
024import jakarta.mail.PasswordAuthentication;
025import jakarta.mail.Session;
026import jakarta.mail.Transport;
027import jakarta.mail.internet.MimeMessage;
028import java.time.Duration;
029import java.util.Date;
030import java.util.Map;
031import java.util.Optional;
032import java.util.Properties;
033import java.util.logging.Level;
034import org.jgrapes.core.Channel;
035import org.jgrapes.core.Components;
036import org.jgrapes.core.Components.Timer;
037import org.jgrapes.core.Event;
038import org.jgrapes.core.Manager;
039import org.jgrapes.core.Subchannel;
040import org.jgrapes.core.annotation.Handler;
041import org.jgrapes.core.events.Start;
042import org.jgrapes.mail.events.OpenMailSender;
043import org.jgrapes.mail.events.SendMailMessage;
044import org.jgrapes.util.Password;
045
046/**
047 * A component that sends mail using a system wide or user specific
048 * connection.
049 * 
050 * The system wide connection is created upon the start of the component.
051 * Additional connections can be created by firing events of type 
052 * {@link OpenMailSender}.
053 */
054@SuppressWarnings("PMD.AvoidSynchronizedStatement")
055public class MailSender
056        extends MailConnectionManager<MailSender.SenderChannel, Event<?>> {
057
058    private Duration maxIdleTime = Duration.ofMinutes(1);
059    private SenderChannel systemChannel;
060
061    /**
062     * Creates a new component base with its channel set to the given 
063     * channel. As a special case {@link Channel#SELF} can be
064     * passed to the constructor to make the component use itself
065     * as channel. The special value is necessary as you 
066     * obviously cannot pass an object to be constructed to its 
067     * constructor.
068     *
069     * @param componentChannel the channel that the component's
070     * handlers listen on by default and that 
071     * {@link Manager#fire(Event, Channel...)} sends the event to
072     */
073    public MailSender(Channel componentChannel) {
074        super(componentChannel);
075    }
076
077    @Override
078    protected boolean connectionsGenerate() {
079        return false;
080    }
081
082    /**
083     * Sets the mail properties. See the Jakarta Mail documentation 
084     * for available settings.
085     *
086     * @param props the props
087     * @return the mail monitor
088     */
089    @Override
090    public MailSender setMailProperties(Map<String, String> props) {
091        mailProps.putAll(props);
092        return this;
093    }
094
095    /**
096     * Sets the maximum idle time. An open connection to the mail server
097     * is closed after this time.
098     *
099     * @param maxIdleTime the new max idle time
100     */
101    public MailSender setMaxIdleTime(Duration maxIdleTime) {
102        this.maxIdleTime = maxIdleTime;
103        return this;
104    }
105
106    /**
107     * Returns the max idle time.
108     *
109     * @return the duration
110     */
111    public Duration maxIdleTime() {
112        return maxIdleTime;
113    }
114
115    @Override
116    protected void configureComponent(Map<String, String> values) {
117        Optional.ofNullable(values.get("maxIdleTime"))
118            .map(Integer::parseInt).map(Duration::ofSeconds)
119            .ifPresent(this::setMaxIdleTime);
120    }
121
122    /**
123     * Start the component.
124     *
125     * @param event the event
126     * @throws MessagingException 
127     */
128    @Handler
129    public void onStart(Start event) throws MessagingException {
130        systemChannel = new SenderChannel(event,
131            channel(), mailProps, password());
132    }
133
134    /**
135     * Open a connection for sending mail as specified by the event.
136     * 
137     * Properties configured for the component are used as fallbacks,
138     * so simply sending an event without specific properties opens
139     * another system connection.
140     *
141     * @param event the event
142     * @param channel the channel
143     * @throws MessagingException 
144     */
145    @Handler
146    public void onOpenMailSender(OpenMailSender event, Channel channel)
147            throws MessagingException {
148        Properties sessionProps = new Properties(mailProps);
149        sessionProps.putAll(event.mailProperties());
150        new SenderChannel(event, channel, sessionProps,
151            event.password().or(this::password));
152    }
153
154    /**
155     * Sends the message as specified by the event.
156     *
157     * @param event the event
158     * @throws MessagingException the messaging exception
159     */
160    @Handler
161    @SuppressWarnings("PMD.CompareObjectsWithEquals")
162    public void onMessage(SendMailMessage event, Channel channel)
163            throws MessagingException {
164        if (channel instanceof SenderChannel chan
165            && chan.mailSender() == this) {
166            chan.sendMessage(event);
167        } else {
168            systemChannel.sendMessage(event);
169        }
170    }
171
172    /**
173     * The specific implementation of the {@link MailChannel}.
174     */
175    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
176    protected class SenderChannel extends MailConnectionManager<
177            MailSender.SenderChannel, Event<?>>.AbstractMailChannel {
178
179        private final Session session;
180        private final Transport transport;
181        private Timer idleTimer;
182
183        /**
184         * Instantiates a new monitor channel.
185         *
186         * @param event the event that triggered the creation
187         * @param mainChannel the main channel (of this {@link Subchannel})
188         * @param sessionProps the session properties
189         * @param password the password
190         * @throws MessagingException the messaging exception
191         */
192        public SenderChannel(Event<?> event, Channel mainChannel,
193                Properties sessionProps, Optional<Password> password)
194                throws MessagingException {
195            super(event, mainChannel);
196            var passwd = password.map(Password::password).map(String::new)
197                .orElse(null);
198            session = Session.getInstance(sessionProps, new Authenticator() {
199                // Workaround for class loading problem in OSGi with j.m. 2.1.
200                // Authenticator's classpath allows accessing provider's
201                // service. See https://github.com/eclipse-ee4j/mail/issues/631
202                @Override
203                protected PasswordAuthentication
204                        getPasswordAuthentication() {
205                    return new PasswordAuthentication(
206                        sessionProps.getProperty("mail.user"), passwd);
207                }
208            });
209            transport = session.getTransport();
210            transport.connect(sessionProps.getProperty("mail.user"), passwd);
211            idleTimer
212                = Components.schedule(timer -> closeConnection(), maxIdleTime);
213        }
214
215        private MailSender mailSender() {
216            return MailSender.this;
217        }
218
219        /**
220         * Send the message provided by the event.
221         *
222         * @param event the event
223         * @throws MessagingException 
224         */
225        @SuppressWarnings("PMD.ReplaceJavaUtilDate")
226        protected void sendMessage(SendMailMessage event)
227                throws MessagingException {
228            synchronized (transport) {
229                if (idleTimer != null) {
230                    idleTimer.cancel();
231                    idleTimer = null;
232                }
233            }
234            Message msg = new MimeMessage(session);
235            if (event.from() != null) {
236                msg.setFrom(event.from());
237            } else {
238                msg.setFrom();
239            }
240            msg.setRecipients(Message.RecipientType.TO, event.to());
241            msg.setRecipients(Message.RecipientType.CC, event.cc());
242            msg.setRecipients(Message.RecipientType.BCC, event.bcc());
243            msg.setSentDate(new Date());
244            for (var header : event.headers().entrySet()) {
245                msg.setHeader(header.getKey(), header.getValue());
246            }
247            msg.setSubject(event.subject());
248            msg.setContent(event.content());
249
250            synchronized (transport) {
251                if (!transport.isConnected()) {
252                    transport.connect();
253                }
254                idleTimer
255                    = Components.schedule(timer -> closeConnection(),
256                        maxIdleTime);
257            }
258            msg.saveChanges();
259            transport.sendMessage(msg, msg.getAllRecipients());
260        }
261
262        @Override
263        public void close() {
264            closeConnection();
265            super.close();
266        }
267
268        /**
269         * Close the connection (not the channel). May be reopened
270         * later if closed due to idle time over.
271         */
272        @SuppressWarnings("PMD.GuardLogStatement")
273        protected void closeConnection() {
274            synchronized (transport) {
275                if (idleTimer != null) {
276                    idleTimer.cancel();
277                    idleTimer = null;
278                }
279                if (transport.isConnected()) {
280                    try {
281                        transport.close();
282                    } catch (MessagingException e) {
283                        logger.log(Level.WARNING,
284                            "Cannot close connection: " + e.getMessage(), e);
285                    }
286                }
287            }
288        }
289
290    }
291
292}