Java SMTPAppenderBase-class And Method Code Example


Here is an example of how to use the logback.core.net.SMTPAppenderBase class to send an email with a log event attached:

import ch.qos.logback.core.net.SMTPAppenderBase;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    public static void main(String[] args) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

        SMTPAppenderBase emailAppender = new SMTPAppenderBase();
        emailAppender.setContext(context);
        emailAppender.setName("email");
        emailAppender.setFrom("[email protected]");
        emailAppender.setSMTPHost("smtp.example.com");
        emailAppender.setSubject("Log Event");
        emailAppender.setSMTPUsername("username");
        emailAppender.setSMTPPassword("password");
        emailAppender.setTo("[email protected]");
        emailAppender.start();

        Logger logger = LoggerFactory.getLogger("Main");
        logger.error("This is an error message");

        emailAppender.stop();
    }
}

In this example, an instance of SMTPAppenderBase is created and configured to send an email from "[email protected]" to "[email protected]" using an SMTP host at "smtp.example.com" with a subject of "Log Event". The SMTP server required a username and password which is set as "username" and "password" respectively.

An error message is logged and that log event is sent as an email.

You'll need to configure your email server accordingly and this could be different for different providers. After using the appender, it's important to stop it by calling stop method in the end.