Example usage for javax.mail Message setRecipients

List of usage examples for javax.mail Message setRecipients

Introduction

In this page you can find the example usage for javax.mail Message setRecipients.

Prototype

public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;

Source Link

Document

Set the recipient addresses.

Usage

From source file:com.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Su solicitud de recuperacin de contrasea ha sido procesada. Su usuario y contrasea para acceder a la plataforma de adopciones son los siguientes:"
                + "\n\n Usuario: " + user + "\n\n Contrasea: " + pass_plano + "\n\n Saludos cordiales, ");

        Transport.send(message);

    } catch (Exception ex) {

    }

    /*catch (MessagingException e) {
     throw new RuntimeException(e);
     }*/
}

From source file:rapture.mail.Mailer.java

public static void email(String[] recipients, String subject, String message) throws MessagingException {
    final SMTPConfig config = getSMTPConfig();
    Session session = getSession(config);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getFrom()));
    InternetAddress[] address = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
        address[i] = new InternetAddress(recipients[i]);
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);//from w  ww . j  a v a  2s.  com
    msg.setContent(message, MediaType.PLAIN_TEXT_UTF_8.toString());
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:NotificationMessage.java

static void sendMail(String toUser, Severity s) {
    // Recipient's email ID needs to be mentioned.
    //String to = "abhiyank@gmail.com";//change accordingly

    // Sender's email ID needs to be mentioned
    String from = "mdtprojectteam16@gmail.com";//change accordingly
    final String username = "mdtprojectteam16";//change accordingly
    final String password = "mdtProject16";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from  w w  w.j  a v a  2s  . c  o m
    });

    try {
        // Create a default MimeMessage object.
        javax.mail.Message message1 = new MimeMessage(session);

        // Set From: header field of the header.
        message1.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));

        // Set Subject: header field
        message1.setSubject("Alert Message From Patient");

        // Now set the actual message
        message1.setText(messageMap.get(s));

        // Send message
        Transport.send(message1);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail2(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Bienvenido al SISTEMA INFORM?TICO DEL REGISTRO NACIONAL DE ADOPCIONES, "
                + "sus credenciales para inscribirse al taller son las siguientes:" + "\n\n Usuario: " + user
                + "\n\n Contrasea: " + pass_plano
                //                    + "\n\n Para ingresar al sistema realizar lo siguiente, "
                //                    + "\n\n"
                //                    + "\n\n"
                //                    + "\n\n A. Click directamente en el siguiente link: "
                //                    + "\n\n"
                //                    + "\n\n       1. Click: http://app.mimp.gob.pe:8080/sirna "
                //                    + "\n\n       2. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n B. En caso no funcione el link, ingresar al sistema desde la pgina web: "
                //                    + "\n\n"
                //                    + "\n\n       1. Ingresar a la pgina web: www.mimp.gob.pe "
                //                    + "\n\n       2. En la barra de men Direcciones Generales? submen Vicemin. Pob. Vulnerables? seleccionar Adopciones? "
                //                    + "\n\n       3. Click en SIRNA Sistema Informtico del Registro Nacional de Adopciones? "
                //                    + "\n\n       4. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n A travs del SIRNA usted podr realizar las siguientes acciones: "
                //                    + "\n\n"
                //                    + "\n\n       - Inscribirse a uno de los talleres programados. "
                //                    + "\n\n       - Descargar las lecturas de su taller. "
                //                    + "\n\n       - Revisar el estado del proceso de adopcin. "
                //                    + "\n\n       - Cambiar su contrasea. "
                //                    + "\n\n"
                //                    + "\n\n Para continuar con el proceso, por favor ingresar al sistema e inscribirse a uno de los talleres programados, hasta un da antes de inicio del taller y/o las bacantes se  "
                //                    + "\n\n encuentres disponibles. "
                + "\n\n"
                + "\n\n De tener alguna complicacin y no fue posible su ingreso al sistema, comunicarse inmediatamente con la unidad de adopcin correspondiente.  "
                + "\n\n" + "\n\n Atentamente, " + "\n\n" + "\n\n Direccin General de Adopciones " + "\n\n"
                + "\n\n Ministerio de la Mujer y Poblaciones Vulnerables " + "\n\n ");

        Transport.send(message);

        /*  } catch (Exception ex) {
         */
    } catch (Exception ex) {

    }

    /*catch (MessagingException e) {
     throw new RuntimeException(e);
     }*/
}

From source file:com.mycompany.craftdemo.utility.java

public static void send(long phno, double price, double profit, String domain, String company) {
    HashMap<String, String> domainMap = new HashMap<>();
    domainMap.put("TMobile", "tmomail.net ");
    domainMap.put("ATT", "txt.att.net");
    domainMap.put("Sprint", "messaging.sprintpcs.com");
    domainMap.put("Verizon", "vtext.com");
    String to = phno + "@" + domainMap.get(domain); //change accordingly

    // Sender's email ID needs to be mentioned
    String from = "uni5prince@gmail.com"; //change accordingly
    final String username = "uni5prince"; //change accordingly
    final String password = "savageph8893"; //change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from ww  w  .jav a2  s  .  c  o m*/
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Prices have gone up!!");

        // Now set the actual message
        message.setText("Hello Jane, Stock prices for " + company + " has reached to $" + price
                + " with profit of $" + profit);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:rapture.mail.Mailer.java

public static void email(CallingContext context, String templateName,
        Map<String, ? extends Object> templateValues) {
    final SMTPConfig config = getSMTPConfig();
    Session session = getSession(config);
    EmailTemplate template = getEmailTemplate(context, templateName);
    try {//from w w  w  .j  a v  a 2  s . c  o  m
        // Instantiate a new MimeMessage and fill it with the required information.
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(config.getFrom()));
        String to = renderTemplate(template.getEmailTo(), templateValues);
        if (StringUtils.isBlank(to)) {
            throw RaptureExceptionFactory.create("No emailTo field");
        }
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(renderTemplate(template.getSubject(), templateValues));
        msg.setSentDate(new Date());
        msg.setContent(renderTemplate(template.getMsgBody(), templateValues), "text/html; charset=utf-8");
        // Hand the message to the default transport service for delivery.
        Transport.send(msg);
    } catch (MessagingException e) {
        log.error("Failed to send email", e);
    }
}

From source file:org.apache.roller.planet.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.// w w w  .  j  av  a 2 s .c  o m
 * 
 * @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(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    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 (mLogger.isDebugEnabled())
            mLogger.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 (mLogger.isDebugEnabled())
                mLogger.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 (mLogger.isDebugEnabled())
                mLogger.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 (mLogger.isDebugEnabled())
                mLogger.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");

    // Try to send while there remain some potentially good addresses
    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.send(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);

    if (bFailedToSome)
        throw sendex;
}

From source file:com.sun.socialsite.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*from   w ww . j a  v  a 2s .co m*/
 *
 * @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(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    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 (mLogger.isDebugEnabled())
            mLogger.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 (mLogger.isDebugEnabled())
                mLogger.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 (mLogger.isDebugEnabled())
                mLogger.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 (mLogger.isDebugEnabled())
                mLogger.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");

    // Try to send while there remain some potentially good addresses
    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
            Startup.getMailProvider().getTransport().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);

    if (bFailedToSome)
        throw sendex;
}

From source file:uk.ac.ox.it.ords.api.project.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////from   w ww  . j a va 2  s . c o  m
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        throw new Exception("Unable to send emails as email server configuration is missing");
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:uk.ac.ox.it.ords.api.database.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////from   ww w  .  j  a va 2 s  .  c  om
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        //throw new Exception("Unable to send emails as email server configuration is missing");
        return; // 
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}