Example usage for javax.mail Session getTransport

List of usage examples for javax.mail Session getTransport

Introduction

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

Prototype

public Transport getTransport(Address address) throws NoSuchProviderException 

Source Link

Document

Get a Transport object that can transport a Message of the specified address type.

Usage

From source file:main.java.vasolsim.common.GenericUtils.java

/**
 * Tests if a given SMTP configuration is valid. It will validate addresses and the port. Then it will test
 * connectivity of the smtp address. Lastly, it will AUTH to smtp server and ensure the information is good.
 *
 * @param address  the SMTP address//from w  w  w  . j  a  v  a  2s.  c  om
 * @param port     the SMTP port
 * @param email    the email address
 * @param password the email address password
 * @param notify   if popup dialogs will appear carrying the servers unsuccessful response message
 *
 * @return if the AUTH was successful
 */
public static boolean isValidSMTPConfiguration(String address, int port, String email, byte[] password,
        boolean notify) {
    if (!isValidAddress(address) || port <= 0 || !isValidEmail(email) || password.length == 0)
        return false;

    try {
        Properties smtpProperties = new Properties();
        smtpProperties.put("mail.smtp.starttls.enable", "true");
        smtpProperties.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(smtpProperties, null);
        Transport transport = session.getTransport("smtp");
        transport.connect(address, port, email, new String(password));
        transport.close();
        return true;
    } catch (Exception e) {
        if (notify) {
            PopupManager.showMessage("Cause:\n" + e.getCause() + "\n\nMessage:\n" + e.getMessage(), "Bad SMTP");

            System.out.println(e.getCause());
            System.out.println(e.getMessage());
        }

        return false;
    }
}

From source file:org.xmlactions.email.EMailSend.java

public static void sendEMail(String fromAddress, String toAddress, String host, String userName,
        String password, String subject, String msg) throws AddressException, MessagingException {

    log.debug(String.format(//  www.ja va 2 s  . co  m
            "sendEMail(from:%s, to:%s, host:%s, userName:%s, password:%s)\nsubject:{" + subject
                    + "\n}\nmessage:{" + msg + "\n}",
            fromAddress, toAddress, host, userName, toPassword(password), subject, msg));
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session;
    if (!StringUtils.isEmpty(password)) {
        props.put("mail.smtp.auth", "true");
        //EMailAuthenticator auth = new EMailAuthenticator(userName + "+" + host, password);
        EMailAuthenticator auth = new EMailAuthenticator(userName, password);
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }

    // Define message
    MimeMessage message = new MimeMessage(session);
    // message.setFrom(new InternetAddress("email_addresses@riostl.com"));
    message.setFrom(new InternetAddress(fromAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(toAddress));
    message.setSubject(subject);
    message.setText(msg);

    // Send message
    if (StringUtils.isEmpty(password)) {
        Transport.send(message);
    } else {
        Provider provider = session.getProvider("smtp");

        Transport transport = session.getTransport(provider);
        // Send message
        transport.connect();
        transport.sendMessage(message, new Address[] { new InternetAddress(toAddress) });
        transport.close();
    }

}

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

public Transport getTransport() throws MailException {
    Transport transport = null;//from   w  w w.  j  a  v  a 2s . co  m

    try {
        Session session = getSession();

        if (_outgoingSecure) {
            transport = session.getTransport("smtps");
        } else {
            transport = session.getTransport("smtp");
        }

        transport.connect(_outgoingHostName, _outgoingPort, _login, _password);

        return transport;
    } catch (MessagingException me) {
        throw new MailException(MailException.ACCOUNT_OUTGOING_CONNECTION_FAILED, me);
    }
}

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

public Transport getTransport(Session session) {
    Transport transport = null;//w  w w  .j  a  v a 2  s  .  co  m
    try {
        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;
}

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

/**
 *
 * @param emailFrom//  w w  w  . j  a v  a2s .  c  o  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:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//from   w w  w.  j a  va 2s.c o  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.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:edu.harvard.med.screensaver.service.SmtpEmailService.java

private void sendMessage(String subject, String message, InternetAddress from, InternetAddress[] recipients,
        InternetAddress[] cclist, File attachedFile) throws MessagingException, IOException {
    log.info("try to send: " + printEmail(subject, message, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
    log.info("host: " + host + ", useSMTPS: " + useSmtps);
    Properties props = new Properties();
    String protocol = "smtp";
    if (useSmtps) // need smtps to test with gmail
    {//from   w  w  w .  j  a va 2s.  c  o m
        props.put("mail.smtps.auth", "true");
        protocol = "smtps";
    }
    Session session = Session.getDefaultInstance(props, null);
    Transport t = session.getTransport(protocol);

    try {
        MimeMessage msg = new MimeMessage(session);
        if (this.replyTos != null)
            msg.setReplyTo(replyTos);
        msg.setFrom(from);
        msg.setSubject(subject);

        if (attachedFile != null) {
            setFileAsAttachment(msg, message, attachedFile);
        } else {
            msg.setContent(message, "text/plain");
        }

        msg.addRecipients(Message.RecipientType.TO, recipients);
        if (cclist != null)
            msg.addRecipients(Message.RecipientType.CC, cclist);

        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        t.close();
    }
    log.info("sent: " + printEmailHeader(subject, from, this.replyTos, recipients, cclist,
            (attachedFile == null ? "" : "" + attachedFile.getCanonicalFile())));
}

From source file:isl.FIMS.utils.Utils.java

public static boolean sendEmail(String to, String subject, String context) {
    boolean isSend = false;

    try {//from  www  .  ja v a2 s  .co m

        String host = "smtp.gmail.com";
        String user = emailAdress;
        String password = emailPass;

        String port = "587";
        String from = "no-reply-" + systemName + "@gmail.com";
        Properties props = System.getProperties();

        props.put("mail.smtp.user", user);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        //  props.put("mail.debug", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable", "true");
        //     props.put("mail.smtp.socketFactory.port", port);
        //    props.put("mail.smtp.socketFactory.class",
        //            "javax.net.ssl.SSLSocketFactory");
        //    props.put("mail.smtp.port", "465");

        Session session = Session.getInstance(props, null);
        //session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        // To get the array of addresses
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject(subject, "UTF-8");
        message.setContent(context, "text/html; charset=UTF-8");
        Transport transport = session.getTransport("smtp");
        try {
            transport.connect(host, user, password);
            transport.sendMessage(message, message.getAllRecipients());
        } finally {
            transport.close();
        }
        isSend = true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return isSend;

}

From source file:com.warsaw.data.controller.LoginController.java

private boolean sendEmail(String to) {
    Properties properties = System.getProperties();
    // Setup mail server
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", HOST);
    properties.put("mail.smtp.user", EMAIL);
    properties.put("mail.smtp.password", PASS);
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.setProperty("mail.transport.protocol", "smtp");

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {/*from w ww .  ja v  a 2s  . c o  m*/
        Message msg = this.buildEmail(session, to);
        /*   Transport transport = session.getTransport();
           transport.send(msg);*/
        Transport transport = session.getTransport("smtp");
        transport.connect(HOST, EMAIL, PASS);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    } catch (Exception e) {
        System.out.println("Ex :" + e);
        return false;
    }

    return true;
}

From source file:org.springframework.mail.javamail.JavaMailSenderImpl.java

/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol./*from   w  ww . j  a v  a2s .  co m*/
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
    return session.getTransport(getProtocol());
}