FYI
Date: Thu, 31 Oct 2002 11:43:30 -0500
To: [EMAIL PROTECTED]
From: Chris Butler <[EMAIL PROTECTED]>
Subject: Ceki Gülcü - quick note (log4j)
Ceki,
Could be useful to have a AuthSMTPAppender for log4j.
Some SMTP servers require authentication before sending.
Don't wanna waste your time or muck up code base if
it's not appropriate though.
Attached is the class extending SMTPAppender. Change as desired.
Hope it is helpful.
Chris
----
--
Ceki
TCP implementations will follow a general principle of robustness: be
conservative in what you do, be liberal in what you accept from
others. -- Jon Postel, RFC 793
package org.apache.log4j.net;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import java.util.Properties;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.ErrorCode;
public class AuthSMTPAppender extends SMTPAppender {
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it. It pulls the username
* and password from log4j.properties or where appropriate.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = _user;
String password = _password;
return new PasswordAuthentication(username, password);
}
}
private String _user;
private String _password;
public String getUser() {
return _user;
}
public void setUser(String user) {
_user = user;
}
public String getPassword() {
return _password;
}
public void setPassword(String password) {
_password = password;
}
/**
* Overrode activeOptions() to have authentication
*/
public void activateOptions() {
Properties props = new Properties (System.getProperties());
if (getSMTPHost() != null) {
props.put("mail.smtp.host", getSMTPHost());
}
// New authentication bit
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// Session session = Session.getInstance(props, null);
//session.setDebug(true);
msg = new MimeMessage(session);
try {
if (getFrom() != null) {
msg.setFrom(getAddress(getFrom()));
} else {
msg.setFrom();
}
msg.setRecipients(Message.RecipientType.TO, parseAddress(getTo()));
if (getSubject() != null) {
msg.setSubject(getSubject());
}
} catch(MessagingException e) {
LogLog.error("Could not activate SMTPAppender options.", e );
}
}
}
--
To unsubscribe, e-mail: <mailto:log4j-dev-unsubscribe@;jakarta.apache.org>
For additional commands, e-mail: <mailto:log4j-dev-help@;jakarta.apache.org>