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.bia.gmailjava.EmailService.java

/**
 *
 * @param addressTo/*w w  w .j  a  v a 2  s  .c  o  m*/
 * @param subject
 * @param message
 * @throws AddressException
 * @throws MessagingException
 */
private void send(InternetAddress[] addressTo, String subject, String message)
        throws AddressException, MessagingException {
    Message msg = new MimeMessage(createSession());
    InternetAddress addressFrom = new InternetAddress(USERNAME);
    msg.setFrom(addressFrom);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // set bcc
    //InternetAddress[] bcc1 = getBCC();
    //msg.setRecipients(Message.RecipientType.BCC, bcc1);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    //String message = comment;
    msg.setContent(message, EMAIL_CONTENT_TYPE);

    Transport.send(msg);
}

From source file:org.sventon.mail.MailNotifier.java

/**
 * @param logEntry       Log entry/*ww w . j  ava  2  s.co  m*/
 * @param repositoryName Name
 * @param mailTemplate   Template
 * @return Message
 * @throws MessagingException If a message exception occurs.
 * @throws IOException        if a IO exception occurs while creating the data source.
 */
private Message createMessage(final LogEntry logEntry, RepositoryName repositoryName, String mailTemplate)
        throws MessagingException, IOException {
    final Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.BCC, receivers.toArray(new InternetAddress[receivers.size()]));
    msg.setSubject(formatSubject(subject, logEntry.getRevision(), repositoryName));

    msg.setDataHandler(
            new DataHandler(new ByteArrayDataSource(HTMLCreator.createRevisionDetailBody(mailTemplate, logEntry,
                    baseURL, repositoryName, dateFormat, null), "text/html")));

    msg.setHeader("X-Mailer", "sventon");
    msg.setSentDate(new Date());
    return msg;
}

From source file:org.sventon.repository.observer.MailNotifier.java

/**
 * @param logEntry       Log entry/* w  ww . j  av  a 2s .c  o m*/
 * @param repositoryName Name
 * @param mailTemplate   Template
 * @return Message
 * @throws MessagingException If a message exception occurs.
 * @throws IOException        if a IO exception occurs while creating the data source.
 */
private Message createMessage(final SVNLogEntry logEntry, RepositoryName repositoryName, String mailTemplate)
        throws MessagingException, IOException {
    final Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.BCC, receivers.toArray(new InternetAddress[receivers.size()]));
    msg.setSubject(formatSubject(subject, logEntry.getRevision(), repositoryName));

    msg.setDataHandler(
            new DataHandler(new ByteArrayDataSource(HTMLCreator.createRevisionDetailBody(mailTemplate, logEntry,
                    baseUrl, repositoryName, dateFormat, null), "text/html")));

    msg.setHeader("X-Mailer", "sventon");
    msg.setSentDate(new Date());
    return msg;
}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content) {
    Message msg = new MimeMessage(session);
    try {/* w ww. j  a  v a  2  s .c o m*/
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(title);
        if (to != null) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }
        //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));
        msg.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(msg);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

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

private void sendMail() throws MailException {
    javax.mail.Session session = null;/*from  w w w. j  av a 2s.  co 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, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

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

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

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

}

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

private void sendMail(LDAPUser user) throws MailException {
    javax.mail.Session session = null;/*www  .j av a 2  s . co 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, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

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

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

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

}

From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java

private void sendHTML(final String message) throws MessagingException, IOException {
    if (message == null || message.isEmpty()) {
        throw new IllegalArgumentException("message");
    }/*w  w  w  .ja va2  s  . c  o m*/

    final String host = properties.getConfigString("host");

    final Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);

    final String port = properties.getConfigString("port", null);
    if (port != null) {
        props.setProperty("mail.smtp.port", port);
    }

    if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) {
        props.setProperty("mail.smtp.ssl.enable", "true");
    }

    final Session session = Session.getInstance(props, null);
    //        session.setDebug( true );

    final javax.mail.Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(properties.getConfigString("from")));

    msg.setRecipients(javax.mail.Message.RecipientType.TO,
            InternetAddress.parse(properties.getConfigString("to"), false));

    msg.setSubject("superpipes error message");

    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html")));

    msg.setHeader("X-Mailer", "superpipes");

    Transport t = null;
    try {
        t = session.getTransport("smtp");

        final String username = properties.getConfigString("username", null);
        final String password = properties.getConfigString("password", null);
        if (username == null || password == null) {
            t.connect();
        } else {
            if (port == null || port.isEmpty()) {
                t.connect(host, username, password);
            } else {
                t.connect(host, Integer.parseInt(port), username, password);
            }
        }

        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }
}

From source file:org.geoserver.wps.mail.SendMail.java

/**
 * Send an EMail to a specified address.
 * //from   w  ww.  ja  va  2 s .  com
 * @param address the to address
 * @param subject the email address
 * @param body message to send
 * @throws MessagingException the messaging exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void send(String address, String subject, String body) {
    try {
        // Session session = Session.getDefaultInstance(props, null);
        Session session = Session.getDefaultInstance(props,
                (conf.getMailSmtpAuth().equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(conf.getUserName(), conf.getPassword());
                    }
                } : null));

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(conf.getFromAddress(), conf.getFromAddressname()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
        message.setSubject(subject);
        message.setText(body.toString());

        Transport.send(message);

    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

}

From source file:com.appeligo.search.messenger.Messenger.java

/**
 * /* w  w w  .  j a va2s. co  m*/
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

From source file:SendMailImpl.java

public void sendMessage(String from, String[] recipients, String subject, String message)
        throws MessagingException {
    boolean debug = false;

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);/*from  w  w  w  .j a  v  a  2s  .c  o m*/

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

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

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

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