View Javadoc
1   /*
2    * Copyright (c) 2002-2014, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.service.mail;
35  
36  import fr.paris.lutece.portal.service.daemon.Daemon;
37  import fr.paris.lutece.portal.service.util.AppLogService;
38  import fr.paris.lutece.portal.service.util.AppPropertiesService;
39  
40  import org.apache.log4j.Logger;
41  
42  import java.util.Date;
43  import java.util.List;
44  
45  import javax.mail.MessagingException;
46  import javax.mail.NoSuchProviderException;
47  import javax.mail.SendFailedException;
48  import javax.mail.Session;
49  import javax.mail.Transport;
50  import javax.mail.internet.AddressException;
51  
52  
53  /**
54   * MailSender Daemon
55   */
56  public class MailSenderDaemon extends Daemon
57  {
58      private static final String PROPERTY_MAIL_HOST = "mail.server";
59      private static final String PROPERTY_MAIL_PORT = "mail.server.port";
60      private static final String PROPERTY_MAIL_DEAMON_WAITTIME = "mail.daemon.waittime";
61      private static final String PROPERTY_MAIL_DEAMON_COUNT = "mail.daemon.count";
62      private static final String PROPERTY_MAIL_USERNAME = "mail.username";
63      private static final String PROPERTY_MAIL_PASSWORD = "mail.password";
64      private static final int DEFAULT_SMTP_PORT = 25;
65  
66      /**
67       * {@inheritDoc}
68       */
69      @Override
70      public synchronized void run(  )
71      {
72          Logger logger = Logger.getLogger( "lutece.mail" );
73          logger.setAdditivity( false );
74  
75          String strHost = AppPropertiesService.getProperty( PROPERTY_MAIL_HOST );
76          String strUsername = AppPropertiesService.getProperty( PROPERTY_MAIL_USERNAME, null );
77          String strPassword = AppPropertiesService.getProperty( PROPERTY_MAIL_PASSWORD, null );
78          int nStmpPort = AppPropertiesService.getPropertyInt( PROPERTY_MAIL_PORT, DEFAULT_SMTP_PORT );
79          int nWaitTime = AppPropertiesService.getPropertyInt( PROPERTY_MAIL_DEAMON_WAITTIME, 1 );
80          int nCount = AppPropertiesService.getPropertyInt( PROPERTY_MAIL_DEAMON_COUNT, 1000 );
81  
82          // Initializes a mail session with the SMTP server
83          StringBuilder sbLogs = new StringBuilder(  );
84          StringBuilder sbLogsLine;
85          IMailQueue queue = MailService.getQueue(  );
86  
87          if ( queue.size(  ) != 0 )
88          {
89              sbLogs.append( new Date(  ).toString(  ) );
90  
91              Session session = MailUtil.getMailSession( strHost, nStmpPort, strUsername, strPassword );
92              Transport transportSmtp = null;
93  
94              try
95              {
96                  transportSmtp = MailUtil.getTransport( session );
97              }
98              catch ( NoSuchProviderException e )
99              {
100                 AppLogService.error( e );
101             }
102 
103             if ( transportSmtp != null )
104             {
105                 try
106                 {
107                     transportSmtp.connect( strHost, nStmpPort, strUsername, strPassword );
108 
109                     MailItem mail = queue.consume(  );
110                     int count = 0;
111 
112                     while ( mail != null )
113                     {
114                         try
115                         {
116                             if ( mail.isUniqueRecipientTo(  ) )
117                             {
118                                 List<String> listAdressTo = MailUtil.getAllStringAdressOfRecipients( mail.getRecipientsTo(  ) );
119 
120                                 for ( String strAdressTo : listAdressTo )
121                                 {
122                                     sbLogsLine = new StringBuilder(  );
123                                     //just one recipient by mail
124                                     mail.setRecipientsTo( strAdressTo );
125                                     sendMail( mail, strHost, transportSmtp, session, sbLogsLine );
126                                     logger.info( sbLogsLine.toString(  ) );
127                                     sbLogs.append( "\r\n" );
128                                     sbLogs.append( sbLogsLine );
129                                 }
130                             }
131                             else
132                             {
133                                 sbLogsLine = new StringBuilder(  );
134                                 sendMail( mail, strHost, transportSmtp, session, sbLogsLine );
135                                 logger.info( sbLogsLine.toString(  ) );
136                                 sbLogs.append( "\r\n" );
137                                 sbLogs.append( sbLogsLine );
138                             }
139                         }
140                         catch ( MessagingException e )
141                         {
142                             //if the connection is dead or not in the connected state
143                             //we put the mail in the queue before end process
144                             queue.send( mail );
145 
146                             break;
147                         }
148 
149                         mail = queue.consume(  );
150 
151                         // Tempo
152                         count++;
153 
154                         if ( ( count % nCount ) == 0 )
155                         {
156                             transportSmtp.close(  );
157                             wait( nWaitTime );
158                             transportSmtp.connect(  );
159                         }
160                     }
161 
162                     transportSmtp.close(  );
163                 }
164                 catch ( MessagingException e )
165                 {
166                     sbLogs.append( "MailService - Error sending mail (MessagingException): " );
167                     sbLogs.append( e.getMessage(  ) );
168                     AppLogService.error( "MailService - Error sending mail (MessagingException): " + e.getMessage(  ), e );
169                 }
170                 catch ( Exception e )
171                 {
172                     sbLogs.append( "MailService - Error sending mail : " );
173                     sbLogs.append( e.getMessage(  ) );
174                     AppLogService.error( "MailService - Error sending mail : " + e.getMessage(  ), e );
175                 }
176             }
177 
178             //reset all resource stored in MailAttachmentCacheService
179             MailAttachmentCacheService.getInstance(  ).resetCache(  );
180             setLastRunLogs( sbLogs.toString(  ) );
181         }
182         else
183         {
184             sbLogs.append( "\r\nNo mail to send " );
185             sbLogs.append( new Date(  ).toString(  ) );
186             logger.debug( sbLogs.toString(  ) );
187         }
188     }
189 
190     /**
191      * send mail
192      * @param mail the mail item
193      * @param strHost the host
194      * @param transportSmtp the smtp transport
195      * @param session the session smtp
196      * @param sbLogsLine the log line
197      * @throws MessagingException @see MessagingException
198      */
199     private void sendMail( MailItem mail, String strHost, Transport transportSmtp, Session session,
200         StringBuilder sbLogsLine ) throws MessagingException
201     {
202         try
203         {
204             sbLogsLine.append( " - To " );
205             sbLogsLine.append( ( ( mail.getRecipientsTo(  ) != null ) ? mail.getRecipientsTo(  ) : "" ) );
206             sbLogsLine.append( " - Cc " );
207             sbLogsLine.append( ( mail.getRecipientsCc(  ) != null ) ? mail.getRecipientsCc(  ) : "" );
208             sbLogsLine.append( " - Bcc " );
209             sbLogsLine.append( ( mail.getRecipientsBcc(  ) != null ) ? mail.getRecipientsBcc(  ) : "" );
210             sbLogsLine.append( " - Subject : " );
211             sbLogsLine.append( mail.getSubject(  ) );
212 
213             switch ( mail.getFormat(  ) )
214             {
215                 case MailItem.FORMAT_HTML:
216                     MailUtil.sendMessageHtml( mail.getRecipientsTo(  ), mail.getRecipientsCc(  ),
217                         mail.getRecipientsBcc(  ), mail.getSenderName(  ), mail.getSenderEmail(  ),
218                         mail.getSubject(  ), mail.getMessage(  ), transportSmtp, session );
219 
220                     break;
221 
222                 case MailItem.FORMAT_TEXT:
223                     MailUtil.sendMessageText( mail.getRecipientsTo(  ), mail.getRecipientsCc(  ),
224                         mail.getRecipientsBcc(  ), mail.getSenderName(  ), mail.getSenderEmail(  ),
225                         mail.getSubject(  ), mail.getMessage(  ), transportSmtp, session );
226 
227                     break;
228 
229                 case MailItem.FORMAT_MULTIPART_HTML:
230                     MailUtil.sendMultipartMessageHtml( mail.getRecipientsTo(  ), mail.getRecipientsCc(  ),
231                         mail.getRecipientsBcc(  ), mail.getSenderName(  ), mail.getSenderEmail(  ),
232                         mail.getSubject(  ), mail.getMessage(  ), mail.getUrlsAttachement(  ),
233                         mail.getFilesAttachement(  ), transportSmtp, session );
234 
235                     break;
236 
237                 case MailItem.FORMAT_MULTIPART_TEXT:
238                     MailUtil.sendMultipartMessageText( mail.getRecipientsTo(  ), mail.getRecipientsCc(  ),
239                         mail.getRecipientsBcc(  ), mail.getSenderName(  ), mail.getSenderEmail(  ),
240                         mail.getSubject(  ), mail.getMessage(  ), mail.getFilesAttachement(  ), transportSmtp, session );
241 
242                     break;
243 
244                 case MailItem.FORMAT_CALENDAR:
245                     MailUtil.sendMessageCalendar( mail.getRecipientsTo(  ), mail.getRecipientsCc(  ),
246                         mail.getRecipientsBcc(  ), mail.getSenderName(  ), mail.getSenderEmail(  ),
247                         mail.getSubject(  ), mail.getMessage(  ), mail.getCalendarMessage(  ), mail.getCreateEvent(  ),
248                         transportSmtp, session );
249 
250                     break;
251 
252                 default:
253                     break;
254             }
255 
256             sbLogsLine.append( " - Status [ OK ]" );
257         }
258         catch ( AddressException e )
259         {
260             //a wrongly formatted address is encountered in the list of recipients
261             sbLogsLine.append( " - Status [ Failed ] : " );
262             sbLogsLine.append( e.getMessage(  ) );
263             AppLogService.error( "MailService - Error sending mail : " + e.getMessage(  ), e );
264         }
265         catch ( SendFailedException e )
266         {
267             //the send failed because of invalid addresses.
268             sbLogsLine.append( " - Status [ Failed ] : " );
269             sbLogsLine.append( e.getMessage(  ) );
270             AppLogService.error( "MailService - Error sending mail : " + e.getMessage(  ), e );
271         }
272         catch ( MessagingException e )
273         {
274             //if the connection is dead or not in the connected state
275             //we put the mail in the queue before end process
276             sbLogsLine.append( " - Status [ Failed ] : " );
277             sbLogsLine.append( e.getMessage(  ) );
278             AppLogService.error( "MailService - Error sending mail : " + e.getMessage(  ), e );
279             throw e;
280         }
281     }
282 }