Example usage for javax.mail Session setDebug

List of usage examples for javax.mail Session setDebug

Introduction

In this page you can find the example usage for javax.mail Session setDebug.

Prototype

public synchronized void setDebug(boolean debug) 

Source Link

Document

Set the debug setting for this Session.

Usage

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom/*from  w ww  .  ja v  a  2 s .  co  m*/
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:com.fsrin.menumine.common.message.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *///from  w ww  .  j a  v a  2 s.  com
public boolean send() {

    try {

        Properties props = new Properties();

        props.put("mail.smtp.host", host.getAddress());

        if (host.useAuthentication()) {

            props.put("mail.smtp.auth", "true");
        }

        Session s = Session.getInstance(props, null);

        s.setDebug(true);

        //            PasswordAuthentication pa = new PasswordAuthentication(host
        //                    .getUsername(), host.getPassword());
        //
        //            URLName url = new URLName(host.getAddress());
        //
        //            s.setPasswordAuthentication(url, pa);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());

        e.printStackTrace();
        throw new RuntimeException(e);

    }

    return true;
}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private void init(InputStream file) throws MessagingException {
    Properties props = System.getProperties();
    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(true);
    message = new MimeMessage(mailSession, file);
}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom// www .j av  a2  s .c  om
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}

From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java

/**
 * Retrieves the system properties and configure a mail session.
 * @return an initialized session./*from  w w  w.j a v a2s  .c o  m*/
 * @see <code>RFC1891</code>
 */
private Session getMailSession(SmtpConfiguration smtpConfiguration) {
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", smtpConfiguration.getServer());
    properties.put("mail.smtp.auth", String.valueOf(smtpConfiguration.isAuthenticate()));
    Session session = Session.getInstance(properties, null);
    // print on the console all SMTP messages.
    session.setDebug(smtpConfiguration.isDebug());
    // Returning the session.
    return session;
}

From source file:edu.stanford.muse.email.MboxEmailStore.java

public Store connect() throws MessagingException {
    // Get a Session object
    // can customize javamail properties here if needed, see e.g. http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html

    Session session = Session.getInstance(mstorProps, null);
    session.setDebug(DEBUG);

    // Get a Store object
    Store store = session.getStore(new URLName("mstor:" + Util.devNullPath())); // although "store" is irrelevant with mbox, connect/close may still be attempted on it. thus, use /dev/null rather than leaving it at / or unspecified path (which may trigger file io error).
    store.connect();/* w w  w .ja  va  2s.com*/
    return store;
}

From source file:org.apache.syncope.core.provisioning.java.job.notification.NotificationJobDelegate.java

@Override
public void afterPropertiesSet() throws Exception {
    if (mailSender instanceof JavaMailSenderImpl) {
        JavaMailSenderImpl javaMailSender = (JavaMailSenderImpl) mailSender;

        Properties javaMailProperties = javaMailSender.getJavaMailProperties();

        Properties props = PropertyUtils.read(Encryptor.class, "mail.properties", "conf.directory").getLeft();
        for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
            String prop = (String) e.nextElement();
            if (prop.startsWith("mail.smtp.")) {
                javaMailProperties.setProperty(prop, props.getProperty(prop));
            }//from   w w  w .j a va2  s.c o  m
        }

        if (StringUtils.isNotBlank(javaMailSender.getUsername())) {
            javaMailProperties.setProperty("mail.smtp.auth", "true");
        }

        javaMailSender.setJavaMailProperties(javaMailProperties);

        String mailDebug = props.getProperty("mail.debug", "false");
        if (BooleanUtils.toBoolean(mailDebug)) {
            Session session = javaMailSender.getSession();
            session.setDebug(true);
            session.setDebugOut(new PrintStream(new LogOutputStream(LOG)));
        }
    }
}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);/*from ww w. j a  v a  2s  . co m*/

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

private MimeMessage getMessage(Address[] addressArray, String from, String content, String title)
        throws MessagingException {
    Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
    session.setDebug(false);
    SMTPMessage msg = new SMTPMessage(session);
    if (StringUtils.isNotEmpty(from)) {
        InternetAddress ss;/*from ww  w.java2s. c  o m*/
        try {
            ss = new InternetAddress(m_bag.m_fromAddress.getAddress(),
                    MimeUtility.encodeText(from, "gb2312", "b"));
            msg.setFrom(ss);
        } catch (UnsupportedEncodingException e) {
            msg.setFrom(m_bag.m_fromAddress);
        }
        msg.setReplyTo(new InternetAddress[] { new InternetAddress(from) });
    } else {
        msg.setFrom(m_bag.m_fromAddress);
    }
    msg.setRecipients(Message.RecipientType.TO, addressArray);
    try {
        msg.setSubject(MimeUtility.encodeText(title, UTF_8, "B"));
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage(), e);
    }
    msg.setSentDate(new Date());
    msg.setContent(content, EMAIL_CONTENT_TYPE);
    return msg;
}

From source file:edu.stanford.muse.email.MboxEmailStore.java

public Folder openFolderWithoutCount(Store s, String fname) throws MessagingException {
    if (fname == null)
        fname = "INBOX";

    // ignore the store coming in, we need a new session and store
    // for each folder

    Session session = Session.getInstance(mstorProps, null);
    session.setDebug(DEBUG);

    // Get a Store object
    Store store = session.getStore(new URLName("mstor:" + fname));
    store.connect();//from w w  w.j a v a2s  .com

    //This is the root folder in the namespace provided
    //see http://docs.oracle.com/javaee/5/api/javax/mail/Store.html#getDefaultFolder%28%29
    Folder folder = store.getDefaultFolder();
    if (folder == null)
        throw new RuntimeException("Invalid folder: " + fname);

    log.info("Opening folder " + Util.blurPath(fname) + " in r/o mode...");
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException me) {
        folder = null;
    }

    return folder;
}