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:org.silverpeas.core.mail.engine.SmtpMailSender.java

/**
 * This method performs the treatment of the technical send:
 * <ul>//from   www . j a  v  a2  s.  co m
 * <li>connection to the SMTP server</li>
 * <li>sending</li>
 * <li>closing the connection</li>
 * </ul>
 * @param mail the original data from which the given {@link MimeMessage} has been initialized.
 * @param smtpConfiguration the SMTP configuration.
 * @param session the current mail session.
 * @param messageToSend the technical message to send.
 * @param batchedToAddresses the receivers of the message.
 * @throws MessagingException
 */
private void performSend(final MailToSend mail, final SmtpConfiguration smtpConfiguration, Session session,
        MimeMessage messageToSend, List<InternetAddress[]> batchedToAddresses) throws MessagingException {

    // Creating a Transport connection (TCP)
    final Transport transport;
    if (smtpConfiguration.isSecure()) {
        transport = session.getTransport(SmtpConfiguration.SECURE_TRANSPORT);
    } else {
        transport = session.getTransport(SmtpConfiguration.SIMPLE_TRANSPORT);
    }

    // Adding send reporting listener
    transport.addTransportListener(new SmtpMailSendReportListener(mail));

    try {
        if (smtpConfiguration.isAuthenticate()) {
            transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(),
                    smtpConfiguration.getUsername(), smtpConfiguration.getPassword());
        } else {
            transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), null, null);
        }

        for (InternetAddress[] toAddressBatch : batchedToAddresses) {
            messageToSend.setRecipients(mail.getTo().getRecipientType().getTechnicalType(), toAddressBatch);
            transport.sendMessage(messageToSend, toAddressBatch);
        }

    } finally {
        try {
            transport.close();
        } catch (Exception e) {
            SilverTrace.error("mail", "SmtpMailSender.send()", "root.EX_IGNORED", "ClosingTransport", e);
        }
    }
}

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 {/*www  .  j  a  v a 2  s  .  com*/
        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: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 {/*  w w w. j a  v  a2 s  .  co  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();
    }

}

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

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

    try {//ww w.j av a 2  s . co 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:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*from  w  w w.  j  ava 2s.c  o m*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {/*from w  w  w  .j  a  v  a 2s .  c om*/
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.mime.charset", "UTF-8");
        props.put("mail.smtp.ssl.enable", ssl);

        Session session = Session.getInstance(props, new EmailAuthenticator(username, password));

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, ""));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject(subject);
        message.setText(content, "utf-8", "html");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException | UnsupportedEncodingException ex) {
        log.error(
                "?  ? email,  : "
                        + ex.getLocalizedMessage());
        ex.printStackTrace();
    }

}

From source file:com.agiletec.plugins.jpwebmail.aps.system.services.webmail.WebMailManager.java

@Override
public void sendMail(MimeMessage msg, String username, String password) throws ApsSystemException {
    //WebMailConfig config = this.getConfig();
    String smtpUsername = this.checkSmtpAuthUsername(username);
    String smtpPassword = this.checkSmtpAuthUserPassword(password);
    //String smtpUsername = (config.isSmtpEntandoUserAuth()) ? username : config.getSmtpUserName();
    //String smtpPassword = (config.isSmtpEntandoUserAuth()) ? password : config.getSmtpPassword();
    //Session session = this.createSession(true, smtpUsername, smtpPassword);
    Session session = (msg instanceof JpMimeMessage) ? ((JpMimeMessage) msg).getSession()
            : this.createSession(true, smtpUsername, smtpPassword);
    Transport bus = null;//from www.ja  va  2 s .  c o m
    try {
        bus = session.getTransport("smtp");
        //StringUtils.isEmpty(bus)
        if (StringUtils.isBlank(smtpUsername) && StringUtils.isBlank(smtpPassword)) {
            bus.connect();
        }
        /*
        if ((smtpUsername != null && smtpUsername.trim().length()>0) && 
              (smtpPassword != null && smtpPassword.trim().length()>0)) {
           if (port != null && port.intValue() > 0) {
              bus.connect(config.getSmtpHost(), port.intValue(), smtpUsername, smtpPassword);
           } else {
              bus.connect(config.getSmtpHost(), smtpUsername, smtpPassword);
           }
        } else {
           bus.connect();
        }
        */
        //bus.connect();
        msg.saveChanges();
        bus.send(msg);
    } catch (Throwable t) {
        _logger.error("Error sending mail", t);
        //ApsSystemUtils.logThrowable(t, this, "sendMail", "Error sending mail");
        throw new ApsSystemException("Error sending mail", t);
    } finally {
        closeTransport(bus);
    }
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void noAuth() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250 OK").build().start(PORT);

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    try {/*www  .j a  va  2  s . co m*/
        transport.connect("localhost", PORT, "zimbra", "secret");
        Assert.fail();
    } catch (MessagingException e) {
        Assert.assertEquals("The server doesn't support SMTP-AUTH.", e.getMessage());
    }
    server.shutdown(1000);
}

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void noAuthMechansims() throws Exception {
    server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO
            .sendLine("250-OK").sendLine("250 AUTH NTLM").build().start(PORT);

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    try {/*w ww  .j a v a  2 s . c  om*/
        transport.connect("localhost", PORT, "zimbra", "secret");
        Assert.fail();
    } catch (MessagingException e) {
        Assert.assertEquals("No auth mechanism supported: [NTLM]", e.getMessage());
    }
    server.shutdown(1000);
}

From source file:com.wso2telco.workflow.notification.EmailService.java

public void sendEmail(final String emailAddress, final String subject, final String content) {

    new Thread() {
        @Override/* ww w .j a  v  a  2 s .c  o m*/
        public void run() {
            Map<String, String> workflowProperties = WorkflowProperties.loadWorkflowPropertiesFromXML();
            String emailHost = workflowProperties.get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_HOST);
            String fromEmailAddress = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_ADDRESS);
            String fromEmailPassword = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_PASSWORD);

            Properties props = System.getProperties();
            props.put("mail.smtp.host", emailHost);
            props.put("mail.smtp.user", fromEmailAddress);
            props.put("mail.smtp.password", fromEmailPassword);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");

            try {
                Session session = Session.getDefaultInstance(props, null);
                InternetAddress toAddress = new InternetAddress(emailAddress);

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(fromEmailAddress));
                message.addRecipient(Message.RecipientType.TO, toAddress);
                message.setSubject(subject);
                message.setContent(content, "text/html; charset=UTF-8");

                Transport transport = session.getTransport("smtp");
                transport.connect(emailHost, fromEmailAddress, fromEmailPassword);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

            } catch (Exception e) {
                log.error("Email sending failed. ", e);
            }
        }
    }.start();
}