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:Mailer.java

/** Send the message.
 *//*from ww w  .j  a  va  2s  .  co m*/
public synchronized void doSend() throws MessagingException {

    if (!isComplete())
        throw new IllegalArgumentException("doSend called before message was complete");

    /** Properties object used to pass props into the MAIL API */
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);

    // Create the Session object
    if (session == null) {
        session = Session.getDefaultInstance(props, null);
        if (verbose)
            session.setDebug(true); // Verbose!
    }

    // create a message
    final Message mesg = new MimeMessage(session);

    InternetAddress[] addresses;

    // TO Address list
    addresses = new InternetAddress[toList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) toList.get(i));
    mesg.setRecipients(Message.RecipientType.TO, addresses);

    // From Address
    mesg.setFrom(new InternetAddress(from));

    // CC Address list
    addresses = new InternetAddress[ccList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) ccList.get(i));
    mesg.setRecipients(Message.RecipientType.CC, addresses);

    // BCC Address list
    addresses = new InternetAddress[bccList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) bccList.get(i));
    mesg.setRecipients(Message.RecipientType.BCC, addresses);

    // The Subject
    mesg.setSubject(subject);

    // Now the message body.
    mesg.setText(body);

    // Finally, send the message! (use static Transport method)
    // Do this in a Thread as it sometimes is too slow for JServ
    // new Thread() {
    // public void run() {
    // try {

    Transport.send(mesg);

    // } catch (MessagingException e) {
    // throw new IllegalArgumentException(
    // "Transport.send() threw: " + e.toString());
    // }
    // }
    // }.start();
}

From source file:Model.DAO.java

public void sendEmail(int id, String status) {
    SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm");
    Properties props = new Properties();
    /** Parmetros de conexo com servidor Gmail */
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("seuemail@gmail.com", "suasenha");
        }/*from  w  w  w . ja va  2 s. com*/
    });

    /** Ativa Debug para sesso */

    try {
        PreparedStatement stmt = this.conn
                .prepareStatement("SELECT * FROM Reservation re WHERE idReservas = ?");
        stmt.setInt(1, id);
        ResultSet rs = stmt.executeQuery();
        rs.next();
        String date = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[0];
        String time = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[1];
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("pck1993@gmail.com")); //Remetente

        Address[] toUser = InternetAddress //Destinatrio(s)
                .parse(rs.getString("email"));

        message.setRecipients(Message.RecipientType.TO, toUser);
        message.setSubject("Status Reserva");//Assunto
        message.setText("Email de alterao do status da resreva no dia " + date + " s " + time
                + " horas para " + status);
        /**Mtodo para enviar a mensagem criada*/
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (SQLException ex) {
        Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:it.infn.ct.security.actions.RegisterUser.java

private void sendMail(UserRequest usreq) throws MailException {
    javax.mail.Session session = null;//  w ww  .j  a  v a2s  .  c  o m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        log.error("Mail resource lookup error");
        log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(usreq.getPreferredMail(),
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        String ccMail[] = mailCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_",
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:it.cnr.icar.eric.server.event.EmailNotifier.java

private void postMail(String endpoint, String message, String subject, String contentType)
        throws MessagingException {

    // get the SMTP address
    String smtpHost = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.host");

    // get the FROM address
    String fromAddress = RegistryProperties.getInstance()
            .getProperty("eric.server.event.EmailNotifier.smtp.from", "eric@localhost");

    // get the TO address that follows 'mailto:'
    String recipient = endpoint.substring(7);

    String smtpPort = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.port",
            null);//from w  w w  .j a va 2  s.  c  o m

    String smtpAuth = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.auth",
            null);

    String smtpDebug = RegistryProperties.getInstance()
            .getProperty("eric.server.event.EmailNotifier.smtp.debug", "false");

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.debug", smtpDebug);
    props.put("mail.smtp.host", smtpHost);
    if ((smtpPort != null) && (smtpPort.length() > 0)) {
        props.put("mail.smtp.port", smtpPort);
    }
    Session session;
    if ("tls".equals(smtpAuth)) {
        // get the username
        String userName = RegistryProperties.getInstance()
                .getProperty("eric.server.event.EmailNotifier.smtp.user", null);

        String password = RegistryProperties.getInstance()
                .getProperty("eric.server.event.EmailNotifier.smtp.password", null);

        Authenticator authenticator = new MyAuthenticator(userName, password);
        props.put("mail.user", userName);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        session = Session.getInstance(props, authenticator);
    } else {
        session = Session.getInstance(props);
    }

    session.setDebug(Boolean.valueOf(smtpDebug).booleanValue());

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(fromAddress);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[1];
    addressTo[0] = new InternetAddress(recipient);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, contentType);
    Transport.send(msg);
}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Message createMimeMessage(Session session, String subject)
        throws UnsupportedEncodingException, MessagingException {

    Message mimeMessage = new MimeMessage(session);
    String from = getPropertyValue(MAIL_FROM);
    mimeMessage.setFrom(new InternetAddress(from));

    EmailDto dto = model.getObject();/*from w  w  w. java 2  s  .  co  m*/

    InternetAddress mailTo[] = convertEmailAddress(dto.getTo());
    mimeMessage.setRecipients(Message.RecipientType.TO, mailTo);

    String mailCc = dto.getCc();
    if (StringUtils.isNotEmpty(mailCc)) {
        mimeMessage.setRecipients(Message.RecipientType.CC, convertEmailAddress(mailCc));
    }
    String mailBcc = dto.getBcc();
    if (StringUtils.isNotEmpty(mailBcc)) {
        mimeMessage.setRecipients(Message.RecipientType.BCC, convertEmailAddress(mailBcc));
    }
    mimeMessage.setSubject(subject);

    return mimeMessage;
}

From source file:checkwebsite.Mainframe.java

/**
 *
 * @param email/*from   w ww.  j a  v  a  2 s .c o m*/
 * @param msg
 */
protected void notify(String email, String msg) {
    // Recipient's email ID needs to be mentioned.
    String to = email;//change accordingly

    // go to link below and turn on Access for less secure apps
    //https://www.google.com/settings/security/lesssecureapps
    // Sender's email ID needs to be mentioned
    String from = "";//Enter your email id here
    final String username = "";//Enter your email id here
    final String password = "";//Enter your password here

    // 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);
        }
    });

    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("Report of your website : " + wurl);

        //            // Now set the actual message
        //            message.setText("Hello, " + msg + " this is sample for to check send "
        //                    + "email using JavaMailAPI ");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Please! find your website report in attachment");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "WebsiteReport.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);
        lblWarning.setText("report sent...");
        System.out.println("Sent message successfully....");

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

From source file:esg.node.components.notification.ESGNotifier.java

private boolean sendNotification(String userid, String userAddress, String messageText) {
    Message msg = null;
    boolean success = false;
    String myAddress = null;//from   w ww. j  av  a2  s.  c o  m

    try {
        msg = new MimeMessage(session);
        msg.setHeader("X-Mailer", "ESG DataNode IshMailer");
        msg.setSentDate(new Date());
        myAddress = props.getProperty("mail.admin.address", "esg-admin@llnl.gov");
        msg.setFrom(new InternetAddress(myAddress));
        msg.setSubject(subject + "ESG File Update Notification");

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userAddress));
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(userAddress));

        msg.setText(messageText);

        Transport.send(msg);
        success = true;
    } catch (MessagingException ex) {
        log.error("Problem Sending Email Notification: to " + userid + ": " + userAddress + " (" + subject
                + ")\n" + messageText + "\n", ex);
    }

    msg = null; //gc niceness

    return success;
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 */// www.  j  av a2  s.c  om
private Message createMessage(String from, String to, String bcc, String subject, String content)
        throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);

        message.setContent(content, "text/html");
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        message.setSubject(subject);
        message.setText(content);
        message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new Bug("Unable to create the message.", e);
    }
}

From source file:com.jvoid.customers.customer.service.CustomerMasterService.java

public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("test@example.com", "test123");
        }/*w w w . jav a  2 s. c  o  m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("toaddress@example.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Reset Password");
        String content = "Your new password is " + password;
        message.setText(content);
        Transport.send(message);

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

From source file:com.photon.phresco.util.Utility.java

public static void sendNewPassword(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }//from w w  w.  j ava2  s  . c o  m
    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.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        message.setContent(body, "text/html");
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}