Example usage for javax.mail Message getAllRecipients

List of usage examples for javax.mail Message getAllRecipients

Introduction

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

Prototype

public Address[] getAllRecipients() throws MessagingException 

Source Link

Document

Get all the recipient addresses for the message.

Usage

From source file:de.mmichaelis.maven.mojo.MailDevelopersMojoTest.java

@Test
public void testFullyConfiguredMail() throws Exception {
    final MavenProject project = mock(MavenProject.class);
    when(project.getDevelopers()).thenReturn(Arrays.asList(developers));
    mojoWrapper.setProject(project);/* w w  w. j  a v a 2 s. co  m*/
    mojoWrapper.setCharset("UTF-8");
    mojoWrapper.setExpires("2");
    final String from = "John Doe <johndoe@github.com>";
    mojoWrapper.setFrom(from);
    mojoWrapper.setPriority("high");
    final String subject = "testFullyConfiguredMail";
    mojoWrapper.setSubject(subject);
    final String topic = "MyTopic";
    mojoWrapper.setTopic(topic);
    final Date now = new Date();
    mojoWrapper.execute();
    final Mailbox inbox = Mailbox.get(developers[0].getEmail());
    assertEquals("One new email for the first developer.", 1, inbox.size());
    final Message message = inbox.get(0);
    assertTrue("Sent date should signal to be today.", DateUtils.isSameDay(now, message.getSentDate()));
    assertEquals("Size of recipients should match number of developers.", developers.length,
            message.getAllRecipients().length);
    final Address[] senders = message.getFrom();
    assertNotNull("Sender address should be set.", senders);
    assertEquals("Number of senders should be 1.", 1, senders.length);
    assertEquals("Sender in message should match original sender.", from, senders[0].toString());
    final String messageSubject = message.getSubject();
    assertTrue("Subject should contain original subject.", messageSubject.contains(subject));
    assertTrue("Subject should contain topic.", messageSubject.contains(topic));

    // TODO: Check additional headers
}

From source file:hudson.maven.reporters.MavenMailerTest.java

private void assertContainsRecipient(String email, Message message) throws Exception {
    assert email != null;
    assert !email.trim().equals("");
    boolean containRecipient = false;
    for (Address address : message.getAllRecipients()) {
        if (email.equals(address.toString())) {
            containRecipient = true;/*w w w  .j  a v a 2 s  .c  o  m*/
            break;
        }
    }
    assert containRecipient;
}

From source file:com.warsaw.data.controller.LoginController.java

private boolean sendEmail(String to) {
    Properties properties = System.getProperties();
    // Setup mail server
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", HOST);
    properties.put("mail.smtp.user", EMAIL);
    properties.put("mail.smtp.password", PASS);
    properties.put("mail.smtp.port", "587");
    properties.put("mail.smtp.auth", "true");
    properties.setProperty("mail.transport.protocol", "smtp");

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {/*  ww  w . j  a v a 2s.c o  m*/
        Message msg = this.buildEmail(session, to);
        /*   Transport transport = session.getTransport();
           transport.send(msg);*/
        Transport transport = session.getTransport("smtp");
        transport.connect(HOST, EMAIL, PASS);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    } catch (Exception e) {
        System.out.println("Ex :" + e);
        return false;
    }

    return true;
}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

protected void sendEmail(EmailConfiguration config, String recipientAddress, String subject, String body) {
    String mailHost = config.getMailServer();
    Boolean mailUseSMTPS = config.isSMTPS();
    String mailUser = config.getUsername();
    String mailPassword = config.getPassword();

    if (mailHost == null) {
        throw new HobsonRuntimeException("No mail host is configured; unable to execute e-mail action");
    } else if (mailUseSMTPS && mailUser == null) {
        throw new HobsonRuntimeException(
                "No mail server username is configured for SMTPS; unable to execute e-mail action");
    } else if (mailUseSMTPS && mailPassword == null) {
        throw new HobsonRuntimeException(
                "No mail server password is configured for SMTPS; unable to execute e-mail action");
    }//from w  w w . j  a  v  a2s  . co m

    // create mail session
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);
    Session session = Session.getDefaultInstance(props, null);

    // create the mail message
    Message msg = createMessage(session, config, recipientAddress, subject, body);

    // send the message
    String protocol = mailUseSMTPS ? "smtps" : "smtp";
    int port = mailUseSMTPS ? 465 : 25;
    try {
        Transport transport = session.getTransport(protocol);
        logger.debug("Sending e-mail to {} using {}@{}:{}", msg.getAllRecipients(), mailUser, mailHost, port);
        transport.connect(mailHost, port, mailUser, mailPassword);
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        logger.debug("Message sent successfully");
    } catch (MessagingException e) {
        logger.error("Error sending e-mail message", e);
        throw new HobsonRuntimeException("Error sending e-mail message", e);
    }
}

From source file:common.email.MailServiceImpl.java

/**
 * this method sends email using a given template
 * @param subject subject of a mail/*from   w ww  . j  a va 2 s.co  m*/
 * @param recipientEmail email receiver adress
 * @param mail mail text to send
 * @param from will be set
* @return true if send succeed
* @throws java.io.FileNotFoundException
 * @throws java.io.IOException
 */
protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException {
    try {
        Properties props = new Properties();
        //props.put("mailHost", mailHost);

        Session session = Session.getInstance(props);
        // construct the message
        javax.mail.Message msg = new javax.mail.internet.MimeMessage(session);
        if (from == null) {
            msg.setFrom();
        } else {
            try {
                msg.setFrom(new InternetAddress(from));
            } catch (MessagingException ex) {
                logger.error(ex);
            }
        }
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        //msg.setHeader("", user)
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8")));

        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        t.connect(mailHost, user, password);
        Address[] a = msg.getAllRecipients();
        t.sendMessage(msg, a);
        t.close();
        return true;
    } catch (MessagingException ex) {
        logger.error(ex);
        ex.printStackTrace();
        return false;
    }

}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void sendMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc,
        String subject, String body, List<MailFile> mailFiles) throws PortalException {

    Folder jxFolder = null;//  w  ww . j  av a  2s .  c o  m

    try {
        jxFolder = openFolder(_account.getSentFolderId());

        Message jxMessage = createMessage(personalName, sender, to, cc, bcc, subject, body, mailFiles);

        Transport transport = _imapConnection.getTransport();

        transport.sendMessage(jxMessage, jxMessage.getAllRecipients());

        transport.close();

        jxFolder.addMessageCountListener(new IMAPMessageCountListener(_user, _account, _password));

        jxFolder.appendMessages(new Message[] { jxMessage });
    } catch (MessagingException me) {
        throw new MailException(me);
    } catch (UnsupportedEncodingException uee) {
        throw new MailException(uee);
    } finally {
        closeFolder(jxFolder, false);
    }
}

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  w w  .ja  va 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
            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:com.vaushell.superpipes.dispatch.ErrorMailer.java

private void sendHTML(final String message) throws MessagingException, IOException {
    if (message == null || message.isEmpty()) {
        throw new IllegalArgumentException("message");
    }/*from  w w  w.java  2  s.  com*/

    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.zilverline.core.IMAPCollection.java

/**
 * Index one message./*from   w  w w.j  av  a2s .  c  o m*/
 */
private void indexMessage(final Document doc, final Message m) throws MessagingException, IOException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return;
    }
    final long uid = ((UIDFolder) m.getFolder()).getUID(m);

    // form a URL that mozilla seems to accept. Couldn't get it to accept
    // what I thought was the standard

    String urlPrefix = "imap://" + user + "@" + host + ":143/fetch%3EUID%3E/";

    final String url = urlPrefix + m.getFolder().getFullName() + "%3E" + uid;
    doc.add(Field.Text("name", url));

    final String subject = m.getSubject();
    final Date recv = m.getReceivedDate();
    final Date sent = m.getSentDate();
    log.info("Folder: " + m.getFolder().getFullName() + ": Message received " + recv + ", subject: " + subject);
    // -------------------------------------------------------
    // data gathered, now add to doc

    if (subject != null) {
        doc.add(Field.Text(F_SUBJECT, m.getSubject()));
        doc.add(Field.Text("title", m.getSubject()));
    }

    if (recv != null) {
        doc.add(Field.Keyword(F_RECEIVED, DateTools.timeToString(recv.getTime(), DateTools.Resolution.SECOND)));
    }

    if (sent != null) {
        doc.add(Field.Keyword(F_SENT, DateTools.timeToString(sent.getTime(), DateTools.Resolution.SECOND)));
        // store date as yyyyMMdd
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dfString = df.format(new Date(sent.getTime()));
        doc.add(Field.Keyword("modified", dfString));
    }

    doc.add(Field.Keyword(F_URL, url));

    Address[] addrs = m.getAllRecipients();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_TO, "" + addrs[j]));
        }
    }

    addrs = m.getFrom();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_FROM, "" + addrs[j]));
            doc.add(Field.Keyword("author", "" + addrs[j]));
        }
    }
    addrs = m.getReplyTo();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_REPLY_TO, "" + addrs[j]));
        }
    }

    doc.add(Field.Keyword(F_UID, "" + uid));

    // could ignore docs that have the deleted flag set
    for (int j = 0; j < FLAGS.length; j++) {
        boolean val = m.isSet(FLAGS[j]);
        doc.add(Field.Keyword(SFLAGS[j], (val ? "true" : "false")));
    }

    // now special case for mime
    if (m instanceof MimeMessage) {
        // mime++;
        MimeMessage mm = (MimeMessage) m;
        log.debug("index, adding MimeMessage " + m.getFileName());
        indexMimeMessage(doc, mm);

    } else {
        // nmime++;

        final DataHandler dh = m.getDataHandler();
        log.debug("index, adding (non-MIME) Content " + m.getFileName());
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(dh.getInputStream())));
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;/*  w  w w  .  j  a  va2  s. c  o  m*/
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // 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
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}