Example usage for javax.mail Transport isConnected

List of usage examples for javax.mail Transport isConnected

Introduction

In this page you can find the example usage for javax.mail Transport isConnected.

Prototype

public synchronized boolean isConnected() 

Source Link

Document

Is this service currently connected?

Usage

From source file:lucee.runtime.net.mail.SMTPVerifier.java

private static boolean _verify(String host, String username, String password, int port)
        throws MessagingException {
    boolean hasAuth = !StringUtil.isEmpty(username);

    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (hasAuth)//w  w  w.  ja v  a  2 s. c o  m
        props.put("mail.smtp.auth", "true");
    if (hasAuth)
        props.put("mail.smtp.user", username);
    if (hasAuth)
        props.put("mail.transport.connect-timeout", "30");
    if (port > 0)
        props.put("mail.smtp.port", String.valueOf(port));

    Authenticator auth = null;
    if (hasAuth)
        auth = new DefaultAuthenticator(username, password);
    Session session = Session.getInstance(props, auth);

    Transport transport = session.getTransport("smtp");
    if (hasAuth)
        transport.connect(host, username, password);
    else
        transport.connect();
    boolean rtn = transport.isConnected();
    transport.close();

    return rtn;
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message//from   www  . ja  va2 s .c om
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:at.molindo.notify.channel.mail.SimpleMailClient.java

private Transport connectTransport() throws MailException {
    try {/*w  w w  .  j av a 2  s . c  om*/
        Transport t = _smtpSession.getTransport("smtp");
        if (isConnect() && !t.isConnected()) {
            t.connect();
        }
        return t;
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("no SMTP provider?", e);
    } catch (MessagingException e) {
        throw new MailException("can't connect to SMTP server", e, true);
    }
}

From source file:com.liferay.mail.imap.IMAPConnection.java

protected void testOutgoingConnection() throws MailException {
    StopWatch stopWatch = new StopWatch();

    stopWatch.start();// ww  w  . j  a v a 2 s.  c o  m

    try {
        Transport transport = getTransport();

        transport.isConnected();

        transport.close();
    } catch (Exception e) {
        throw new MailException(MailException.ACCOUNT_OUTGOING_CONNECTION_FAILED, e);
    } finally {
        if (_log.isDebugEnabled()) {
            stopWatch.stop();

            _log.debug("Testing outgoing connection completed in " + stopWatch.getTime() + " ms");
        }
    }
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param mimeMessage// w ww.ja  v a  2s. c o m
 * @throws MessagingException
 */
private void _send(MimeMessage mimeMessage) throws MessagingException {

    Transport transport = null;

    try {

        transport = session.getTransport();
        transport.connect();

        mimeMessage.setSentDate(new Date());
        mimeMessage.saveChanges();

        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    } finally {
        if (transport != null && transport.isConnected()) {
            transport.close();
        }
    }
}

From source file:com.cubusmail.mail.MessageHandler.java

/**
 * @throws MessagingException//from  w  w  w  . j a v  a2  s.  co m
 * @throws IOException
 */
public void send() throws MessagingException, IOException {

    buildBodyContent();
    this.message.setHeader("X-Mailer", CubusConstants.APPLICATION_NAME);
    this.message.setSentDate(new Date());

    Transport transport = this.session.getTransport();
    if (!transport.isConnected()) {
        transport.connect();
    }

    transport.sendMessage(this.message, this.message.getAllRecipients());
    transport.close();
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

@Override
public void send(final GmailMessage message) {
    if (message instanceof JavaMailGmailMessage) {
        Transport transport = null;

        try {/*w  ww  .  j  av a  2 s .c o m*/
            final JavaMailGmailMessage msg = (JavaMailGmailMessage) message;
            transport = getGmailTransport();
            transport.sendMessage(msg.getMessage(), msg.getMessage().getAllRecipients());
        } catch (final Exception e) {
            throw new GmailException("Failed sending message: " + message, e);
        } finally {
            if (transport.isConnected()) {
                try {
                    transport.close();
                } catch (final Exception e) {
                    LOG.warn("Cannot Close ImapGmailConnection : " + transport, e);
                }
            }
        }
    } else {
        throw new GmailException("ImapGmailClient requires JavaMailGmailMessage!");
    }
}

From source file:org.libreplan.web.common.ConfigurationController.java

/**
 * Test E-mail connection.// w ww  .  jav  a2  s.  c o  m
 *
 * @param host
 *            the host
 * @param port
 *            the port
 * @param username
 *            the username
 * @param password
 *            the password
 */
private void testEmailConnection(String host, String port, String username, String password) {
    Properties props = System.getProperties();
    Transport transport = null;

    try {
        if ("SMTP".equals(protocolsCombobox.getSelectedItem().getLabel())) {
            props.setProperty("mail.smtp.port", port);
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.connectiontimeout", Integer.toString(3000));
            Session session = Session.getInstance(props, null);

            transport = session.getTransport("smtp");
            if ("".equals(username) && "".equals(password)) {
                transport.connect();
            }
        } else if (STARTTLS_PROTOCOL.equals(protocolsCombobox.getSelectedItem().getLabel())) {
            props.setProperty("mail.smtps.port", port);
            props.setProperty("mail.smtps.host", host);
            props.setProperty("mail.smtps.connectiontimeout", Integer.toString(3000));
            Session session = Session.getInstance(props, null);

            transport = session.getTransport("smtps");
            if (!"".equals(username) && password != null) {
                transport.connect(host, username, password);
            }
        }

        messages.clearMessages();
        if (transport != null) {
            if (transport.isConnected()) {
                messages.showMessage(Level.INFO, _("Connection successful!"));
            } else if (!transport.isConnected()) {
                messages.showMessage(Level.WARNING, _("Connection unsuccessful"));
            }
        }
    } catch (AuthenticationFailedException e) {
        messages.clearMessages();
        messages.showMessage(Level.ERROR, _("Invalid credentials"));
    } catch (MessagingException e) {
        LOG.error(e);
        messages.clearMessages();
        messages.showMessage(Level.ERROR, _("Cannot connect"));
    } catch (Exception e) {
        LOG.error(e);
        messages.clearMessages();
        messages.showMessage(Level.ERROR, _("Failed to connect"));
    }
}

From source file:org.openengsb.connector.email.internal.abstraction.JavaxMailAbstraction.java

public Transport getTransport(Session session) {
    Transport transport = null;
    try {/*from ww  w. j  a v  a 2  s.co m*/
        transport = session.getTransport("smtp");
        log.debug("connecting smtp-transport " + transport);
        transport.connect();
        if (transport.isConnected()) {
            aliveState = AliveState.ONLINE;
        } else {
            aliveState = AliveState.OFFLINE;
        }
        log.debug("State is now " + aliveState);
    } catch (MessagingException e) {
        log.error("could not connect transport ", e);
        aliveState = AliveState.OFFLINE;
        throw new DomainMethodExecutionException(
                "Emailnotifier could not connect (wrong username/password or" + " mail server unavailable) ");
    }
    return transport;
}