1 17 package org.apache.log.output.net; 18 19 import java.util.Date ; 20 import javax.mail.Address ; 21 import javax.mail.Message ; 22 import javax.mail.MessagingException ; 23 import javax.mail.Session ; 24 import javax.mail.Transport ; 25 import javax.mail.internet.MimeMessage ; 26 import org.apache.log.format.Formatter; 27 import org.apache.log.output.AbstractOutputTarget; 28 29 36 public class SMTPOutputLogTarget extends AbstractOutputTarget 37 { 38 private final Session m_session; 40 41 private Message m_message; 43 44 private final Address [] m_toAddresses; 46 47 private final Address m_fromAddress; 49 50 private final String m_subject; 52 53 private int m_msgSize; 55 56 private final int m_maxMsgSize; 58 59 private StringBuffer m_buffer; 61 62 74 public SMTPOutputLogTarget( 75 final Session session, 76 final Address [] toAddresses, 77 final Address fromAddress, 78 final String subject, 79 final int maxMsgSize, 80 final Formatter formatter ) 81 { 82 super( formatter ); 83 84 m_maxMsgSize = maxMsgSize; 86 m_toAddresses = toAddresses; 87 m_fromAddress = fromAddress; 88 m_subject = subject; 89 m_session = session; 90 91 open(); 93 } 94 95 104 protected void write( final String data ) 105 { 106 try 107 { 108 if( m_message == null ) 110 { 111 m_message = new MimeMessage ( m_session ); 112 m_message.setFrom( m_fromAddress ); 113 m_message.setRecipients( Message.RecipientType.TO, m_toAddresses ); 114 m_message.setSubject( m_subject ); 115 m_message.setSentDate( new Date () ); 116 m_msgSize = 0; 117 m_buffer = new StringBuffer (); 118 } 119 120 m_buffer.append( data ); 122 m_buffer.append( '\n' ); 123 ++m_msgSize; 124 125 if( m_msgSize >= m_maxMsgSize ) 127 { 128 send(); 129 } 130 } 131 catch( MessagingException e ) 132 { 133 getErrorHandler().error( "Error creating message", e, null ); 134 } 135 } 136 137 141 public synchronized void close() 142 { 143 super.close(); 144 send(); 145 } 146 147 152 public void setDebug( boolean flag ) 153 { 154 m_session.setDebug( flag ); 155 } 156 157 161 private void send() 162 { 163 try 164 { 165 if( m_message != null && m_buffer != null ) 166 { 167 m_message.setText( m_buffer.toString() ); 168 Transport.send( m_message ); 169 m_message = null; 170 } 171 } 172 catch( MessagingException e ) 173 { 174 getErrorHandler().error( "Error sending message", e, null ); 175 } 176 } 177 } 178 179 | Popular Tags |