001    //$HeadURL: https://svn.wald.intevation.org/svn/deegree/base/branches/2.3_testing/src/org/deegree/framework/mail/MailHelper.java $
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 by:
005       Department of Geography, University of Bonn
006     and
007       lat/lon GmbH
008    
009     This library is free software; you can redistribute it and/or modify it under
010     the terms of the GNU Lesser General Public License as published by the Free
011     Software Foundation; either version 2.1 of the License, or (at your option)
012     any later version.
013     This library is distributed in the hope that it will be useful, but WITHOUT
014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
016     details.
017     You should have received a copy of the GNU Lesser General Public License
018     along with this library; if not, write to the Free Software Foundation, Inc.,
019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020    
021     Contact information:
022    
023     lat/lon GmbH
024     Aennchenstr. 19, 53177 Bonn
025     Germany
026     http://lat-lon.de/
027    
028     Department of Geography, University of Bonn
029     Prof. Dr. Klaus Greve
030     Postfach 1147, 53001 Bonn
031     Germany
032     http://www.geographie.uni-bonn.de/deegree/
033    
034     e-mail: info@deegree.org
035    ----------------------------------------------------------------------------*/
036    package org.deegree.framework.mail;
037    
038    // J2EE 1.2
039    import java.io.File;
040    import java.util.ArrayList;
041    import java.util.Date;
042    import java.util.List;
043    import java.util.Properties;
044    
045    import javax.mail.Message;
046    import javax.mail.Multipart;
047    import javax.mail.PasswordAuthentication;
048    import javax.mail.Session;
049    import javax.mail.Transport;
050    import javax.mail.internet.InternetAddress;
051    import javax.mail.internet.MimeBodyPart;
052    import javax.mail.internet.MimeMessage;
053    import javax.mail.internet.MimeMultipart;
054    
055    import org.deegree.framework.log.ILogger;
056    import org.deegree.framework.log.LoggerFactory;
057    import org.deegree.framework.util.CharsetUtils;
058    import org.deegree.framework.util.StringTools;
059    import org.deegree.i18n.Messages;
060    
061    /**
062     * A helper class to create and send mail.
063     *
064     * @author <a href="mailto:tfr@users.sourceforge.net">Torsten Friebe </A>
065     * @author last edited by: $Author: mschneider $
066     *
067     * @version $Revision: 18195 $,$Date: 2009-06-18 17:55:39 +0200 (Do, 18. Jun 2009) $
068     *
069     * @see javax.mail.Message
070     * @see javax.mail.internet.MimeMessage
071     */
072    
073    public final class MailHelper {
074    
075        private static final ILogger LOG = LoggerFactory.getLogger( MailHelper.class );
076    
077        /**
078         * Creates a mail helper to send a message.
079         *
080         */
081        public MailHelper() {
082            // EMpty And useless ConstructorS not typed with emacs
083        }
084    
085        /**
086         * This method creates an email message and sends it using the J2EE mail services
087         *
088         * @param eMess
089         *            a email message
090         * @param mailHost
091         *            name of the SMTP host
092         *
093         * @throws SendMailException
094         *             an exception if the message is undeliverable
095         */
096        public static void createAndSendMail( MailMessage eMess, String mailHost )
097                                throws SendMailException {
098            Properties p = System.getProperties();
099            p.put( "mail.smtp.host", mailHost );
100            new MailHelper().createAndSendMail( eMess, Session.getDefaultInstance( p ) );
101        }
102    
103        /**
104         * This method creates an email message and sends it using the J2EE mail services
105         *
106         * @param eMess
107         *            a email message
108         * @param mailHost
109         *            name of the SMTP host
110         * @param mailHostUser
111         *            user name for mail host
112         * @param mailHostPassword
113         *            password of user
114         *
115         *
116         * @throws SendMailException
117         *             an exception if the message is undeliverable
118         */
119        public static void createAndSendMail( MailMessage eMess, String mailHost, String mailHostUser,
120                                              String mailHostPassword )
121                                throws SendMailException {
122            Properties p = System.getProperties();
123            p.put( "mail.smtp.host", mailHost );
124            p.setProperty( "mail.smtp.submitter", mailHostUser );
125            p.setProperty( "mail.smtp.auth", "true" );
126            Authenticator authenticator = new Authenticator( mailHostUser, mailHostPassword );
127    
128            new MailHelper().createAndSendMail( eMess, Session.getInstance( p, authenticator ) );
129        }
130    
131        /**
132         * This method creates an email message and sends it using the J2EE mail services
133         *
134         * @param eMess
135         *            a email message
136         * @param mailHost
137         *            name of the SMTP host
138         * @param attachment
139         *            Object to attach to a mail
140         * @param mimeType
141         *            mimetype of the attchment
142         *
143         * @throws SendMailException
144         */
145        public static void createAndSendMail( MailMessage eMess, String mailHost, Object[] attachment, String[] mimeType )
146                                throws SendMailException {
147            Properties p = System.getProperties();
148            p.put( "mail.smtp.host", mailHost );
149            new MailHelper().createAndSendMail( eMess, Session.getDefaultInstance( p ), attachment, mimeType );
150        }
151    
152        /**
153         * This method creates an email message and sends it using the J2EE mail services
154         *
155         * @param eMess
156         *            a email message
157         * @param mailHost
158         *            name of the SMTP host
159         * @param attachment
160         *            Object to attach to a mail
161         * @param mimeType
162         *            mimetype of the attchment
163         * @param mailHostUser
164         *            user name for mail host
165         * @param mailHostPassword
166         *            password of user
167         * @throws SendMailException
168         */
169        public static void createAndSendMail( MailMessage eMess, String mailHost, Object[] attachment, String[] mimeType,
170                                              String mailHostUser, String mailHostPassword )
171                                throws SendMailException {
172            Properties p = System.getProperties();
173            p.put( "mail.smtp.host", mailHost );
174            p.setProperty( "mail.smtp.submitter", mailHostUser );
175            p.setProperty( "mail.smtp.auth", "true" );
176            Authenticator authenticator = new Authenticator( mailHostUser, mailHostPassword );
177    
178            new MailHelper().createAndSendMail( eMess, Session.getInstance( p, authenticator ), attachment, mimeType );
179        }
180    
181        /**
182         * This method creates an email message and sends it using the J2EE mail services
183         *
184         * @param eMess
185         *            a email message
186         * @param mailHost
187         *            name of the SMTP host
188         * @param files
189         *            files to attach to a mail
190         * @param mimeType
191         *            mimetype of the attchment
192         * @throws SendMailException
193         */
194        public static void createAndSendMail( MailMessage eMess, String mailHost, File[] files, String[] mimeType )
195                                throws SendMailException {
196            Properties p = System.getProperties();
197            p.put( "mail.smtp.host", mailHost );
198            new MailHelper().createAndSendMail( eMess, Session.getDefaultInstance( p ), files, mimeType );
199        }
200    
201        /**
202         * This method creates an email message and sends it using the J2EE mail services
203         *
204         * @param eMess
205         *            a email message
206         * @param mailHost
207         *            name of the SMTP host
208         * @param files
209         *            files to attach to a mail
210         * @param mimeType
211         *            mimetype of the attchment
212         * @param mailHostUser
213         * @param mailHostPassword
214         * @throws SendMailException
215         */
216        public static void createAndSendMail( MailMessage eMess, String mailHost, File[] files, String[] mimeType,
217                                              String mailHostUser, String mailHostPassword )
218                                throws SendMailException {
219            Properties p = System.getProperties();
220            p.put( "mail.smtp.host", mailHost );
221            p.setProperty( "mail.smtp.submitter", mailHostUser );
222            p.setProperty( "mail.smtp.auth", "true" );
223            Authenticator authenticator = new Authenticator( mailHostUser, mailHostPassword );
224    
225            new MailHelper().createAndSendMail( eMess, Session.getInstance( p, authenticator ), files, mimeType );
226        }
227    
228        /**
229         * This method creates an email message and sends it using the J2EE mail services
230         *
231         * @param eMess
232         *            a email message
233         * @param session
234         *
235         * @throws SendMailException
236         *             an exception if the message is undeliverable
237         *
238         * @see javax.mail.Transport
239         * @see <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Resources4.html#63060">J2EE Mail Session connection
240         *      </a>
241         */
242        public void createAndSendMail( MailMessage eMess, Session session )
243                                throws SendMailException {
244            createAndSendMail( eMess, session, (Object[]) null, null );
245        }
246    
247        /**
248         * This method creates an email message and sends it using the J2EE mail services
249         *
250         * @param eMess
251         *            a email message
252         * @param session
253         * @param mailHostUser
254         * @param mailHostPassword
255         *
256         * @throws SendMailException
257         *             an exception if the message is undeliverable
258         *
259         * @see javax.mail.Transport
260         * @see <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Resources4.html#63060">J2EE Mail Session connection
261         *      </a>
262         */
263        public void createAndSendMail( MailMessage eMess, Session session, String mailHostUser, String mailHostPassword )
264                                throws SendMailException {
265            createAndSendMail( eMess, session, (Object[]) null, null );
266        }
267    
268        /**
269         * This method creates an email message and sends it using the J2EE mail services
270         *
271         * @param eMess
272         *            an email message
273         * @param session
274         * @param attachment
275         *            Object to attach to a mail
276         * @param mimeType
277         *            mimetype of the attchment
278         * @throws SendMailException
279         *             an exception if the message is undeliverable
280         */
281        public void createAndSendMail( MailMessage eMess, Session session, Object[] attachment, String[] mimeType )
282                                throws SendMailException {
283            if ( eMess == null || !eMess.isValid() ) {
284                throw new SendMailException( "Not a valid e-mail!" );
285            }
286            try {
287                int k = eMess.getMessageBody().length() > 60 ? 60 : eMess.getMessageBody().length() - 1;
288                LOG.logDebug( StringTools.concat( 500, "Sending message, From: ", eMess.getSender(), "\nTo: ",
289                                                  eMess.getReceiver(), "\nSubject: ", eMess.getSubject(), "\nContents: ",
290                                                  eMess.getMessageBody().substring( 0, k ), "..." ) );
291                // construct the message
292                MimeMessage msg = new MimeMessage( session );
293                msg.setFrom( new InternetAddress( eMess.getSender() ) );
294                msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( eMess.getReceiver(), false ) );
295                msg.setSubject( eMess.getSubject(), CharsetUtils.getSystemCharset() );
296                msg.setHeader( "X-Mailer", "JavaMail" );
297                msg.setSentDate( new Date() );
298    
299                // create and fill the first message part
300                List<MimeBodyPart> mbps = new ArrayList<MimeBodyPart>();
301                MimeBodyPart mbp = new MimeBodyPart();
302                mbp.setContent( eMess.getMessageBody(), eMess.getMimeType() );
303                mbps.add( mbp );
304                if ( attachment != null ) {
305                    if ( attachment.length != mimeType.length ) {
306                        throw new SendMailException( Messages.getMessage( "FRAMEWORK_MAIL_ATTACH" ) );
307                    }
308                    for ( int i = 0; i < attachment.length; i++ ) {
309                        mbp = new MimeBodyPart();
310                        mbp.setContent( attachment[i], mimeType[i] );
311                        mbp.setFileName( "file" + i );
312                        mbps.add( mbp );
313                    }
314                }
315                // create the Multipart and add its parts to it
316                Multipart mp = new MimeMultipart();
317                for ( int i = 0; i < mbps.size(); i++ ) {
318                    mp.addBodyPart( mbps.get( i ) );
319                }
320                msg.setContent( mp );
321    
322                // Transport tr = session.getTransport( "smtp" );
323                // if ( mailHostUser != null ) {
324                // tr.connect( mailHostUser, mailHostPassword );
325                // } else {
326                // tr.connect();
327                // }
328                // msg.saveChanges(); // don't forget this
329                // tr.sendMessage( msg, msg.getAllRecipients() );
330                // tr.close();
331    
332                Transport.send( msg );
333                LOG.logDebug( "Mail sent successfully! Header=", eMess.getHeader() );
334            } catch ( Exception e ) {
335                LOG.logError( e.getMessage(), e );
336                String s = Messages.getMessage( "FRAMEWORK_MAIL_SEND_ERROR", eMess.getHeader() );
337                throw new SendMailException( s, e );
338            }
339        }
340    
341        /**
342         * This method creates an email message and sends it using the J2EE mail services
343         *
344         * @param eMess
345         *            an email message
346         * @param session
347         * @param files
348         *            files to attach to a mail
349         * @param mimeType
350         *            mimetype of the attchment
351         * @throws SendMailException
352         *             an exception if the message is undeliverable
353         */
354        public void createAndSendMail( MailMessage eMess, Session session, File[] files, String[] mimeType )
355                                throws SendMailException {
356            if ( eMess == null || !eMess.isValid() ) {
357                throw new SendMailException( "Not a valid e-mail!" );
358            }
359            try {
360                int k = eMess.getMessageBody().length() > 60 ? 60 : eMess.getMessageBody().length() - 1;
361                LOG.logDebug( StringTools.concat( 500, "Sending message, From: ", eMess.getSender(), "\nTo: ",
362                                                  eMess.getReceiver(), "\nSubject: ", eMess.getSubject(), "\nContents: ",
363                                                  eMess.getMessageBody().substring( 0, k ), "..." ) );
364                // construct the message
365                MimeMessage msg = new MimeMessage( session );
366                msg.setFrom( new InternetAddress( eMess.getSender() ) );
367                msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( eMess.getReceiver(), false ) );
368                msg.setSubject( eMess.getSubject(), CharsetUtils.getSystemCharset() );
369                msg.setHeader( "X-Mailer", "JavaMail" );
370                msg.setSentDate( new Date() );
371    
372                // create and fill the first message part
373                List<MimeBodyPart> mbps = new ArrayList<MimeBodyPart>();
374                MimeBodyPart mbp = new MimeBodyPart();
375                mbp.setContent( eMess.getMessageBody(), eMess.getMimeType() );
376                mbps.add( mbp );
377                if ( files != null ) {
378                    if ( files.length != mimeType.length ) {
379                        throw new SendMailException( Messages.getMessage( "FRAMEWORK_MAIL_ATTACH" ) );
380                    }
381                    for ( int i = 0; i < files.length; i++ ) {
382                        mbp = new MimeBodyPart();
383                        mbp.attachFile( files[i] );
384                        mbp.setHeader( "Content-Type", mimeType[i] );
385                        mbps.add( mbp );
386                    }
387                }
388                // create the Multipart and add its parts to it
389                Multipart mp = new MimeMultipart();
390                for ( int i = 0; i < mbps.size(); i++ ) {
391                    mp.addBodyPart( mbps.get( i ) );
392                }
393                msg.setContent( mp );
394    
395                // send the mail off
396                // Transport tr = session.getTransport( "smtp" );
397                // if ( mailHostUser != null ) {
398                // tr.connect( mailHostUser, mailHostPassword );
399                // } else {
400                // tr.connect();
401                // }
402                // msg.saveChanges(); // don't forget this
403                // tr.sendMessage( msg, msg.getAllRecipients() );
404                // tr.close();
405                Transport.send( msg );
406                LOG.logDebug( "Mail sent successfully! Header=", eMess.getHeader() );
407            } catch ( Exception e ) {
408                LOG.logError( e.getMessage(), e );
409                String s = Messages.getMessage( "FRAMEWORK_MAIL_SEND_ERROR", eMess.getHeader() );
410                throw new SendMailException( s, e );
411            }
412        }
413    
414        private static class Authenticator extends javax.mail.Authenticator {
415            private PasswordAuthentication authentication;
416    
417            public Authenticator( String username, String password ) {
418                // String username = "auth-user";
419                // String password = "auth-password";
420                authentication = new PasswordAuthentication( username, password );
421            }
422    
423            @Override
424            protected PasswordAuthentication getPasswordAuthentication() {
425                return authentication;
426            }
427        }
428    
429    }