Example usage for javax.mail Transport sendMessage

List of usage examples for javax.mail Transport sendMessage

Introduction

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

Prototype

public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;

Source Link

Document

Send the Message to the specified list of addresses.

Usage

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send the message/*from w w w  .  j  av a2s  .co  m*/
 *
 * @param msg
 *            the message to send
 * @param transport
 *            the transport used to send the message
 * @throws MessagingException
 *             If a messaging error occured
 * @throws AddressException
 *             If invalid address
 */
private static void sendMessage(Message msg, Transport transport) throws MessagingException, AddressException {
    if (msg.getAllRecipients() != null) {
        // Send the message
        transport.sendMessage(msg, msg.getAllRecipients());
    } else {
        throw new AddressException("Mail adress is null");
    }
}

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);
        }// w ww.j  a  va 2s.  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:isl.FIMS.utils.Utils.java

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

    try {//from   w w  w.  j  ava2s  .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:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {/* www . ja  v a  2s  . c o  m*/
        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:org.apache.roller.weblogger.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*from   www.ja va 2 s.  c  om*/
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(String from, String[] to, String[] cc, String[] bcc, String subject,
        String content, String mimeType) throws MessagingException {

    MailProvider mailProvider = WebloggerStartup.getMailProvider();
    if (mailProvider == null) {
        return;
    }

    Session session = mailProvider.getSession();
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (log.isDebugEnabled())
            log.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (log.isDebugEnabled())
                log.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (log.isDebugEnabled())
                log.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (log.isDebugEnabled())
                log.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    Transport transport = mailProvider.getTransport();

    // Try to send while there remain some potentially good addresses
    try {
        do {
            // Avoid a loop if we are stuck
            nAddresses = remainingAddresses.length;

            try {
                // Send to the list of remaining addresses, ignoring the addresses attached to the message
                transport.sendMessage(message, remainingAddresses);
            } catch (SendFailedException ex) {
                bFailedToSome = true;
                sendex.setNextException(ex);

                // Extract the remaining potentially good addresses
                remainingAddresses = ex.getValidUnsentAddresses();
            }
        } while (remainingAddresses != null && remainingAddresses.length > 0
                && remainingAddresses.length != nAddresses);

    } finally {
        transport.close();
    }

    if (bFailedToSome)
        throw sendex;
}

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 {/*w  w  w. java2  s  .c om*/
        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 {/*from  w  w  w .  j  a  v 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:mx.unam.pixel.controller.MailController.java

public void enviaMensaje(String mensaje) {
    try {/*www .j  av 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: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 w w  w.j  a v a  2 s . 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();
    }

}

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

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

    new Thread() {
        @Override//from   w  w w .  ja va2 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();
}