Example usage for javax.mail Transport connect

List of usage examples for javax.mail Transport connect

Introduction

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

Prototype

public void connect(String user, String password) throws MessagingException 

Source Link

Document

Connect to the current host using the specified username and password.

Usage

From source file:mx.unam.pixel.controller.MailController.java

public void enviaMensaje(String mensaje) {
    try {//from  www.j  a  v a 2 s  .  c om
        Properties props = new Properties();

        // Nombre del host de correo, es smtp.gmail.com
        props.setProperty("mail.smtp.host", "smtp.gmail.com");

        // TLS si est disponible
        props.setProperty("mail.smtp.starttls.enable", "true");

        // Puerto de gmail para envio de correos
        props.setProperty("mail.smtp.port", "587");

        // Nombre del usuario
        props.setProperty("mail.smtp.user", "ejemplo@gmail.com");

        // Si requiere o no usuario y password para conectarse.
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);
        //session.setDebug(true);

        //Construimos el mensage
        MimeMessage message = new MimeMessage(session);
        InternetAddress cuenta = new InternetAddress("enrique.wps@gmail.com");
        message.setFrom(); //Correo electronico que manda el mensaja
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("vampa@ciencias.unam.mx"));
        message.setSubject("Test MUFFIN");
        message.setText("Test Muffin Cuerpo");
        // Abrimos la comunicacion 
        Transport t = session.getTransport("smtp");

        t.connect("dasds@gmail.com", "asdsadas"); // Ususario y contrasea
        t.sendMessage(message, message.getAllRecipients());
        // Cierre
        t.close();

    } catch (AddressException ex) {
        System.err.println("er");
    } catch (MessagingException ex) {
        Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.sourceforge.subsonic.backend.service.EmailSession.java

private void sendMessage(MimeMessage message) throws MessagingException {
    Transport transport = null;
    try {//  w  w  w  .  jav  a2 s. co m
        transport = session.getTransport("smtps");
        transport.connect(USER, password);
        transport.sendMessage(message, message.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }
}

From source file:org.fireflow.service.email.send.MailSenderImpl.java

public void sendEMail(MailMessage mailMessage) throws ServiceInvocationException {

    //1?Session/*from   w w  w .j a v a  2s.  co m*/
    Properties javaMailProperties = new Properties();

    javaMailProperties.put("mail.transport.protocol", mailServiceDef.getProtocol());
    javaMailProperties.put("mail.smtp.host", mailServiceDef.getSmtpServer());
    javaMailProperties.put("mail.smtp.auth", mailServiceDef.isNeedAuth() ? "true" : "false");
    if (mailServiceDef.isUseSSL()) {
        javaMailProperties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        javaMailProperties.setProperty("mail.smtp.socketFactory.fallback", "false");
        javaMailProperties.setProperty("mail.smtp.socketFactory.port",
                Integer.toString(mailServiceDef.getSmtpPort()));
    }

    Session mailSession = Session.getInstance(javaMailProperties);

    //2?MimeMessage
    MimeMessage mimeMsg = null;
    try {
        mimeMsg = createMimeMessage(mailSession, mailMessage);

        //3???
        Transport transport = mailSession.getTransport();
        transport.connect(mailServiceDef.getUserName(), mailServiceDef.getPassword());

        transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
    } catch (AddressException e) {
        throw new ServiceInvocationException(e);
    } catch (MessagingException e) {
        throw new ServiceInvocationException(e);
    }
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {// ww w . ja va2  s . co  m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {

    String passwordDesencriptada = Desencriptar(password2);

    try {//  w  ww. j  a  v a 2s .  com
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ha recibido tu solicitud. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + passwordDesencriptada + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }//from   ww  w  .j a  v  a 2s. c  o m
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:org.opencastproject.kernel.mail.BaseSmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 *
 * @param message/*www  .j  a  va2  s.  co  m*/
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    if (!productionMode) {
        logger.debug("Skipping sending of message {} due to test mode", message);
        return;
    }
    Transport t = getSession().getTransport(mailTransport);
    try {
        if (user != null)
            t.connect(user, password);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:org.opencastproject.kernel.mail.SmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 * //  w ww .j av  a 2  s.  co m
 * @param message
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    Transport t = getSession().getTransport(mailTransport);
    try {
        if (mailUser != null)
            t.connect(mailUser, mailPassword);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 * /*from   w  ww .  ja v a2 s  .c o m*/
 * @param message
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    Transport t = getSession().getTransport(MAIL_TRANSPORT);
    try {
        if (mailUser != null)
            t.connect(mailUser, mailPassword);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:mx.uatx.tesis.managebeans.IndexMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {
    try {/*from  w w  w  .  j  a v  a  2 s.c  om*/
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ta da la bienvenida. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + password2 + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}