package org.apache.log4j.net;

import javax.mail.Session;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import org.apache.log4j.helpers.LogLog;

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.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);
        }
    }
}
