Example usage for javax.mail Transport close

List of usage examples for javax.mail Transport close

Introduction

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

Prototype

public synchronized void close() throws MessagingException 

Source Link

Document

Close this service and terminate its connection.

Usage

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;
    try {//  w  ww.  j  a va  2s .  c  om
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:portal.api.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody, String subj) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    if ((PortalRepository.getPropertyByName("mailhost").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", PortalRepository.getPropertyByName("mailhost").getValue());
    if ((PortalRepository.getPropertyByName("mailuser").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", PortalRepository.getPropertyByName("mailuser").getValue());
    if ((PortalRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!PortalRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", PortalRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = PortalRepository.getPropertyByName("adminEmail").getValue();
    final String username = PortalRepository.getPropertyByName("mailuser").getValue();
    final String password = PortalRepository.getPropertyByName("mailpassword").getValue();

    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//ww  w .  j a  v a2 s .c  o m
    });

    Transport transport;
    try {
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(adminemail, adminemail));

        transport.connect();

        Address[] recips = (Address[]) ArrayUtils.addAll(msg.getRecipients(Message.RecipientType.TO),
                msg.getRecipients(Message.RecipientType.CC));

        transport.sendMessage(msg, recips);

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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/*ww w  .  ja v a 2  s . 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:isl.FIMS.utils.Utils.java

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

    try {/*from  w ww.j a v  a  2 s  . com*/

        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:net.jetrix.mail.MailSessionManager.java

/**
 * Check if the mail session is working properly.
 *///  ww w. j a  v  a 2s .  co  m
public boolean checkSession() {
    boolean check = false;

    if (session != null) {
        try {
            Transport transport = session.getTransport();
            transport.connect();
            transport.close();

            check = true;
        } catch (MessagingException e) {
            log.warning("Unable to validate the mail session (" + e.getMessage() + ")");
        }
    }

    return check;
}

From source file:org.apache.roller.weblogger.business.MailProvider.java

public MailProvider() throws StartupException {

    String connectionTypeString = WebloggerConfig.getProperty("mail.configurationType");
    if ("properties".equals(connectionTypeString)) {
        type = ConfigurationType.MAIL_PROPERTIES;
    }//from   w w  w.j ava 2  s. c  om
    jndiName = WebloggerConfig.getProperty("mail.jndi.name");
    mailHostname = WebloggerConfig.getProperty("mail.hostname");
    mailUsername = WebloggerConfig.getProperty("mail.username");
    mailPassword = WebloggerConfig.getProperty("mail.password");
    try {
        String portString = WebloggerConfig.getProperty("mail.port");
        if (portString != null) {
            mailPort = Integer.parseInt(portString);
        }
    } catch (Throwable t) {
        log.warn("mail server port not a valid integer, ignoring");
    }

    // init and connect now so we fail early
    if (type == ConfigurationType.JNDI_NAME) {
        String name = "java:comp/env/" + jndiName;
        try {
            Context ctx = (Context) new InitialContext();
            session = (Session) ctx.lookup(name);
        } catch (NamingException ex) {
            throw new StartupException("ERROR looking up mail-session with JNDI name: " + name);
        }
    } else {
        Properties props = new Properties();
        props.put("mail.smtp.host", mailHostname);
        if (mailUsername != null && mailPassword != null) {
            props.put("mail.smtp.auth", "true");
        }
        if (mailPort != -1) {
            props.put("mail.smtp.port", "" + mailPort);
        }
        session = Session.getDefaultInstance(props, null);
    }

    try {
        Transport transport = getTransport();
        transport.close();
    } catch (Throwable t) {
        throw new StartupException("ERROR connecting to mail server", t);
    }

}

From source file:com.sun.socialsite.business.MailProvider.java

public MailProvider() throws StartupException {

    String connectionTypeString = Config.getProperty("mail.configurationType");
    if ("properties".equals(connectionTypeString)) {
        type = ConfigurationType.MAIL_PROPERTIES;
    }//from www  .  ja v  a  2s  .c  o  m
    jndiName = Config.getProperty("mail.jndi.name");
    mailHostname = Config.getProperty("mail.hostname");
    mailUsername = Config.getProperty("mail.username");
    mailPassword = Config.getProperty("mail.password");
    try {
        String portString = Config.getProperty("mail.port");
        if (portString != null) {
            mailPort = Integer.parseInt(portString);
        }
    } catch (Throwable t) {
        log.warn("mail server port not a valid integer, ignoring");
    }

    // init and connect now so we fail early
    if (type == ConfigurationType.JNDI_NAME) {
        String name = "java:comp/env/" + jndiName;
        try {
            Context ctx = (Context) new InitialContext();
            session = (Session) ctx.lookup(name);
        } catch (NamingException ex) {
            throw new StartupException("ERROR looking up mail-session with JNDI name: " + name);
        }
    } else {
        Properties props = new Properties();
        props.put("mail.smtp.host", mailHostname);
        if (mailUsername != null && mailPassword != null) {
            props.put("mail.smtp.auth", "true");
        }
        if (mailPort != -1) {
            props.put("mail.smtp.port", "" + mailPort);
        }
        session = Session.getDefaultInstance(props, null);
    }

    try {
        Transport transport = getTransport();
        transport.close();
    } catch (Throwable t) {
        throw new StartupException("ERROR connecting to mail server", t);
    }

}

From source file:easyproject.service.Mail.java

public void sendMail() {
    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

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

    try {//ww w  .  j a va 2 s  .  co  m
        MimeMessage message = new MimeMessage(session);

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message.setSubject(asunto);
        message.setSentDate(new Date());
        message.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message.saveChanges();
        tr.sendMessage(message, message.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:cl.preguntame.controller.PlataformaController.java

@ResponseBody
@RequestMapping(value = "/email", method = RequestMethod.POST)
public String correo(HttpServletRequest req) {

    try {//w w  w. ja v  a2 s.  c  o  m
        String host = "smtp.gmail.com";

        Properties prop = System.getProperties();

        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", "hector.riquelme1169@gmail.com");
        prop.put("mail.smtp.password", "rriiqquueellmmee");
        prop.put("mail.smtp.port", 587);
        prop.put("mail.smtp.auth", "true");

        Session sesion = Session.getDefaultInstance(prop, null);
        MimeMessage mensaje = new MimeMessage(sesion);

        mensaje.setFrom(new InternetAddress());
        mensaje.setRecipient(Message.RecipientType.TO, new InternetAddress("hector.riquelme1169@gmail.com"));
        mensaje.setSubject("CONTACTO MIS CONCEPTOS");
        mensaje.setText(req.getParameter("mensaje_contacto"));

        Transport transport = sesion.getTransport("smtp");
        transport.connect(host, "hector.riquelme1169@gmail.com", "rriiqquueellmmee");
        transport.sendMessage(mensaje, mensaje.getAllRecipients());

        transport.close();

    } catch (Exception e) {

    }

    return req.getParameter("mensaje_contacto") + "  -  " + req.getParameter("email_contacto");
}

From source file:easyproject.utils.SendMail.java

@Override
public void run() {

    Properties props = new Properties();

    props.put("mail.debug", "true");
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", servidorSMTP);
    props.put("mail.smtp.port", puerto);

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

    try {/*from ww  w.j  a va 2s.c o  m*/
        MimeMessage message1 = new MimeMessage(session);

        message1.addRecipient(Message.RecipientType.TO, new InternetAddress(destino));
        message1.setSubject(asunto);
        message1.setSentDate(new Date());
        message1.setContent(mensaje, "text/html; charset=utf-8");

        Transport tr = session.getTransport("smtp");
        tr.connect(servidorSMTP, usuario, password);
        message1.saveChanges();
        tr.sendMessage(message1, message1.getAllRecipients());
        tr.close();

    } catch (MessagingException e) {
        e.printStackTrace();
    }

}