Search code examples
swingjakarta-mail

How to redirect javax.mail.Session setDebug to jTextArea


How can I redirect javax.mail.Session setDebug to jTextArea ?

ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
Session mailSession = Session.getDefaultInstance(props, null);
logger.info("JAVAMAIL debug mode is ON");
mailSession.setDebug(true);
mailSession.setDebugOut(ps);
logger.info(os);

Solution

  • You could use the nice CustomOutputStream class described on http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea:

    import java.io.*;
    import java.util.Properties;
    import javax.mail.Session;
    import javax.swing.*;
    
    public class PrintStream2TextArea {
        public static void main(final String[] arguments) {
            new PrintStream2TextArea().launchGui();
        }
    
        private void launchGui() {
            final JFrame frame = new JFrame("Stack Overflow");
            frame.setBounds(100, 100, 800, 600);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            final JTextArea textArea = new JTextArea(42, 28);
            setupMailSession(new Properties(), textArea);
            frame.getContentPane().add(textArea);
            frame.setVisible(true);
        }
    
        private void setupMailSession(final Properties props, final JTextArea textArea) {
            PrintStream ps = new PrintStream(new CustomOutputStream(textArea));
            Session mailSession = Session.getDefaultInstance(props, null);
            //logger.info("JAVAMAIL debug mode is ON");
            mailSession.setDebug(true);
            mailSession.setDebugOut(ps);
            //logger.info(os);
        }
    
        /**
         * This class extends from OutputStream to redirect output to a JTextArea.
         *
         * @author www.codejava.net
         */
        public static class CustomOutputStream extends OutputStream {
            private JTextArea textArea;
    
            public CustomOutputStream(JTextArea textArea) {
                this.textArea = textArea;
            }
    
            @Override
            public void write(int b) throws IOException {
                // redirects data to the text area
                textArea.append(String.valueOf((char)b));
                // scrolls the text area to the end of data
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }
        }
    }