Example usage for javax.mail.internet MimeMessage setSubject

List of usage examples for javax.mail.internet MimeMessage setSubject

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setSubject.

Prototype

@Override
public void setSubject(String subject) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifySubscriptionDeleted(TemporaryMailContainer container) {
    try {/*from  w w w  .jav a  2  s .  com*/
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        Subscription obj = container.getObj();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s
        //maybe nice to use a template rather then sending raw xml.
        org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription();
        MappingModelToApi.mapSubscription(obj, api);
        String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES);
        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
        attachment.setFileName("uddiNotification.xml");
        mp.addBodyPart(attachment);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey()));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom,
        String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost
    String host = ConfigManager.getInstance().getSmtpMailhost();
    String port = ConfigManager.getInstance().getSmtpMailport();
    String password = ConfigManager.getInstance().getSmtpMailpassword();
    String auth = ConfigManager.getInstance().getSmtpMailauth();
    String sender = ConfigManager.getInstance().getSmtpMailuser();

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.user", sender);
    properties.setProperty("mail.smtp.password", password);
    properties.setProperty("mail.smtp.auth", auth);
    properties.setProperty("mail.smtp.port", port);

    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

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

    // Set From: header field of the header.
    if (!StringUtils.isBlank(sender)) {
        try {/*w w w  .ja  va 2 s .  c  o  m*/
            message.setFrom(new InternetAddress(sender));

        } catch (AddressException ex) {
            logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex);
        } catch (MessagingException ex) {
            logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex);
        }

    }

    List<Address> addresses = new ArrayList<Address>();

    String receivers = emails.getReceivers();
    receivers = StringUtils.trim(receivers);

    for (String receiver : receivers.split(";")) {
        if (!StringUtils.isBlank(receiver)) {
            try {
                addresses.add(new InternetAddress(receiver));
            } catch (AddressException ex) {
                logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex);
            } catch (MessagingException ex) {
                logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex);
            }
        }
    }
    Address[] add = new Address[addresses.size()];
    addresses.toArray(add);
    try {
        message.addRecipients(Message.RecipientType.TO, add);

        // Set Subject: header field
        message.setSubject("[Pundit Contact Form]: " + subject);

        // Now set the actual message
        message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n"
                + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text);

    } catch (MessagingException ex) {
        logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex);
    }
    // Send message

    try {
        logger.log(Level.INFO, "Trying to send message to receivers: {0}",
                Arrays.toString(message.getAllRecipients()));
        transport = session.getTransport("smtp");
        transport.connect(host, sender, password);
        transport.sendMessage(message, message.getAllRecipients());
        logger.log(Level.INFO, "Sent messages to all receivers {0}",
                Arrays.toString(message.getAllRecipients()));
    } catch (NoSuchProviderException nspe) {
        logger.log(Level.SEVERE, "Cannot find smtp provider", nspe);
    } catch (MessagingException me) {
        logger.log(Level.SEVERE, "Cannot set transport layer ", me);
    } finally {
        try {

            transport.close();
        } catch (MessagingException ex) {

        } catch (NullPointerException ne) {
        }

    }

}

From source file:org.cern.flume.sink.mail.MailSink.java

@Override
public Status process() throws EventDeliveryException {
    Status status = null;/* w  ww  .j a  va 2  s  .com*/

    // Start transaction
    Channel ch = getChannel();
    Transaction txn = ch.getTransaction();
    txn.begin();

    try {

        Event event = ch.take();

        if (event != null) {

            // Get system properties
            Properties properties = System.getProperties();

            // Setup mail server
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.port", port);

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

            // Create a default MimeMessage object.
            MimeMessage mimeMessage = new MimeMessage(session);

            // Set From: header field of the header.
            mimeMessage.setFrom(new InternetAddress(sender));

            // Set To: header field of the header.
            for (String recipient : recipients) {
                mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            }

            // Now set the subject and actual message
            Map<String, String> headers = event.getHeaders();

            String value;

            String mailSubject = subject;
            for (String field : subjectFields) {

                try {
                    if (field.equals("body")) {
                        value = new String(event.getBody());
                    } else {
                        value = new String(headers.get(field));
                    }
                } catch (NullPointerException t) {
                    value = "";
                }

                mailSubject = mailSubject.replace("%{" + field + "}", value);
            }

            String mailMessage = message;
            for (String field : messageFields) {

                try {
                    if (field.equals("body")) {
                        value = new String(event.getBody());
                    } else {
                        value = new String(headers.get(field));
                    }
                } catch (NullPointerException t) {
                    value = "";
                }

                mailMessage = mailMessage.replace("%{" + field + "}", value);
            }

            mimeMessage.setSubject(mailSubject);
            mimeMessage.setText(mailMessage);

            // Send message
            Transport.send(mimeMessage);

        }

        txn.commit();
        status = Status.READY;

    } catch (Throwable t) {

        txn.rollback();

        logger.error("Unable to send e-mail.", t);

        status = Status.BACKOFF;

        if (t instanceof Error) {
            throw (Error) t;
        }

    } finally {

        txn.close();

    }

    return status;
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {

    try {/*from w ww.  ja v  a2s  . co m*/
        log.info("Sending notification email to " + notificationEmailAddress + " from "
                + getEMailProperties().getProperty("mail.smtp.from", "jUDDI"));
        if (session != null && notificationEmailAddress != null) {
            MimeMessage message = new MimeMessage(session);
            InternetAddress address = new InternetAddress(notificationEmailAddress);
            Address[] to = { address };
            message.setRecipients(RecipientType.TO, to);
            message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI")));
            //maybe nice to use a template rather then sending raw xml.
            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            Multipart mp = new MimeMultipart();

            MimeBodyPart content = new MimeBodyPart();
            String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body");

            msg_content = String
                    .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName),
                            StringEscapeUtils.escapeHtml(AppConfig.getConfiguration()
                                    .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                            GetSubscriptionType(body), GetChangeSummary(body));

            content.setContent(msg_content, "text/html; charset=UTF-8;");
            mp.addBodyPart(content);

            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
            attachment.setFileName("uddiNotification.xml");
            mp.addBodyPart(attachment);

            message.setContent(mp);
            message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                    + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey());
            Transport.send(message);
        } else {
            throw new DispositionReportFaultMessage("Session is null!", null);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DispositionReportFaultMessage(e.getMessage(), null);
    }

    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}

From source file:mitm.application.djigzo.james.matchers.SubjectPhoneNumber.java

@Override
public Collection<MailAddress> matchMail(Mail mail) throws MessagingException {
    List<MailAddress> matchingRecipients = null;

    String phoneNumber = null;//from w  w  w  .  ja  va  2 s. c  om

    MimeMessage message = mail.getMessage();

    /*
     * We need to check whether the original subject is stored in the mail attributes because
     * the check for the telephone number should be done on the original subject. The reason
     * for this is that the current subject can result in the detection of an incorrect
     * telephone number because the subject was changed because the subject trigger was
     * removed. 
     * 
     * Example:
     *  
     * original subject is: "test 123 [encrypt] 123456". The subject is: "test 123 123456" after
     * the trigger has been removed. The telephone nr 123123456 is detected instead of 123456.
     * 
     * See bug report: https://jira.djigzo.com/browse/GATEWAY-11
     * 
     */
    DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

    String originalSubject = mailAttributes.getOriginalSubject();

    if (originalSubject == null) {
        originalSubject = message.getSubject();
    }

    if (StringUtils.isNotBlank(originalSubject)) {
        Matcher matcher = phoneNumberPattern.matcher(originalSubject);

        if (matcher.find()) {
            phoneNumber = matcher.group();

            /*
             * Remove the match and set the subject without the number. 
             * 
             * Note: the match should be removed from the current subject!!
             * 
             * Note2: using substringBeforeLast is only correct if the pattern matches the end
             * of the subject (which is the default). If the pattern matches something in the
             * middle, substringBeforeLast should not be used.
             */
            message.setSubject(StringUtils.substringBeforeLast(message.getSubject(), phoneNumber));
        }
    }

    if (StringUtils.isNotBlank(phoneNumber)) {
        matchingRecipients = MailAddressUtils.getRecipients(mail);

        int nrOfRecipients = CollectionUtils.getSize(matchingRecipients);

        if (nrOfRecipients == 1) {
            try {
                boolean added = addPhoneNumber(mail, matchingRecipients.get(0), phoneNumber);

                if (!added) {
                    /* 
                     * addPhoneNumbers has more thorough checks to see if the phone 
                     * number is valid and if not, there will be no matcj
                     */
                    matchingRecipients = Collections.emptyList();
                }
            } catch (DatabaseException e) {
                throw new MessagingException("Exception adding phone numbers.", e);
            }
        } else {
            /*
             * A telephone number was found but we cannot add the number to a users account
             * because we do not known to which recipient the number belongs. We will however
             * return all the recipients.
             */
            logger.warn("Found " + nrOfRecipients + " recipients but only one is supported.");
        }
    }

    if (matchingRecipients == null) {
        matchingRecipients = Collections.emptyList();
    }

    return matchingRecipients;
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testEncryptBase64EncodeBug() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setSubject("test");
    message.setContent("test", "text/plain");

    SMIMEBuilder builder = new SMIMEBuilderImpl(message, "to", "subject", "from");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/certificate-base64-encode-bug.cer");

    builder.addRecipient(certificate, SMIMERecipientMode.ISSUER_SERIAL);

    builder.encrypt(SMIMEEncryptionAlgorithm.DES_EDE3_CBC);

    MimeMessage newMessage = builder.buildMessage();

    newMessage.saveChanges();//  w  ww.  ja v a 2  s  .c  om

    File file = new File(tempDir, "testEncryptBase64EncodeBug.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    newMessage.writeTo(new SkipHeadersOutputStream(bos));

    String blob = new String(bos.toByteArray(), "us-ascii");

    // check if all lines are not longer than 76 characters
    LineIterator it = IOUtils.lineIterator(new StringReader(blob));

    while (it.hasNext()) {
        String next = it.nextLine();

        if (next.length() > 76) {
            fail("Line length exceeds 76: " + next);
        }
    }
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

public void send() throws AxisFault {

    try {// w ww. j  av  a 2 s .c o m

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        });
        MimeMessage msg = new MimeMessage(session);

        // Set date - required by rfc2822
        msg.setSentDate(new java.util.Date());

        // Set from - required by rfc2822
        String from = properties.getProperty("mail.smtp.from");
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        }

        EndpointReference epr = null;
        MailToInfo mailToInfo;

        if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) {
            epr = messageContext.getTo();
        }

        if (epr != null) {
            if (!epr.hasNoneAddress()) {
                mailToInfo = new MailToInfo(epr);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));

            } else {
                if (from != null) {
                    mailToInfo = new MailToInfo(from);
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(mailToInfo.getEmailAddress()));
                } else {
                    String error = EMailSender.class.getName() + "Couldn't countinue due to"
                            + " FROM addressing is NULL";
                    log.error(error);
                    throw new AxisFault(error);
                }
            }
        } else {
            // replyto : from : or reply-path;
            if (from != null) {
                mailToInfo = new MailToInfo(from);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));
            } else {
                String error = EMailSender.class.getName() + "Couldn't countinue due to"
                        + " FROM addressing is NULL and EPR is NULL";
                log.error(error);
                throw new AxisFault(error);
            }

        }

        msg.setSubject("__ Axis2/Java Mail Message __");

        if (mailToInfo.isxServicePath()) {
            msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\"");
        }

        if (inReplyTo != null) {
            msg.setHeader(Constants.IN_REPLY_TO, inReplyTo);
        }

        createMailMimeMessage(msg, mailToInfo, format);
        Transport.send(msg);

        log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction());

        sendReceive(messageContext, msg.getMessageID());
    } catch (AddressException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Creates the IMAP messages to be sent. Looks up access (email & pwd) from
 * LDAP, sets the values and returns the messages to be sent.
 * //www. j  a  va  2  s . co  m
 * @param session Mail session 
 * @param emailAddr From email address
 * @param request Request from PS
 * @return Array of messages
 * @throws Exception 
 */
private Message[] createMessage(Session session, String emailAddr, SetMessageRequestType request)
        throws Exception {

    /*
    //DBG ONLY - Check about CC entry.
    List<String> ctlist = request.getContactTo();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: TO="+ ctlist.get(0));
    }
    ctlist = request.getContactCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: CC="+ ctlist.get(0));
    }
    ctlist = request.getContactBCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> createMessage: BCC="+ ctlist.get(0));
    }
    */
    MimeMessage message = new MimeMessage(session);

    if (!CommonUtil.listNullorEmpty(request.getContactTo())) {
        message.setRecipients(Message.RecipientType.TO, getInetAddresses(request.getContactTo())); //getInetAddresses(request, "To"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactCC())) {
        message.setRecipients(Message.RecipientType.CC, getInetAddresses(request.getContactCC())); //getInetAddresses(request, "CC"));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactBCC())) {
        message.setRecipients(Message.RecipientType.BCC, getInetAddresses(request.getContactBCC())); //getInetAddresses(request, "BCC"));
    }

    message.setSubject(request.getSubject());

    // Adding headers doesn't seem to be supported currently in zimbra. 
    // Adding patientId to body instead temporarily 
    // message.addHeader("X-PATIENTID", request.getPatientId());
    StringBuilder sb = new StringBuilder();

    // Only add in PATIENTID first line if there is a patientId in session.
    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        sb.append("PATIENTID=").append(request.getPatientId()).append("\n");
    }

    if (CommonUtil.strNullorEmpty(request.getBody())) {
        sb.append("");
    } else {
        sb.append(request.getBody());
    }

    message.setContent(sb.toString(), "text/plain");
    message.setFrom(new InternetAddress(emailAddr));
    message.setSentDate(new Date());

    List<String> labelList = request.getLabels();
    if (labelList.size() > 0) {
        String label = labelList.get(0);
        if (label.equalsIgnoreCase("starred")) {
            message.setFlag(Flags.Flag.FLAGGED, true);
        }
    }
    Message[] msgArr = new Message[1];
    msgArr[0] = message;
    return msgArr;
}

From source file:org.sakaiproject.tool.mailtool.Mailtool.java

public String processSendEmail() {
    /* EmailUser */ selected = m_recipientSelector.getSelectedUsers();
    if (m_selectByTree) {
        selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers();
        selectedGroupUsers = m_recipientSelector2.getSelectedUsers();
        selectedSectionUsers = m_recipientSelector3.getSelectedUsers();

        selected.addAll(selectedGroupAwareRoleUsers);
        selected.addAll(selectedGroupUsers);
        selected.addAll(selectedSectionUsers);
    }//from  w ww. jav a2 s  . c om
    // Put everyone in a set so the same person doesn't get multiple emails.
    Set emailusers = new TreeSet();
    if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future 
        for (Iterator i = getEmailGroups().iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            emailusers.addAll(group.getEmailusers());
        }
    }
    if (isAllGroupSelected()) {
        for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("section")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllSectionSelected()) {
        for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("group")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllGroupAwareRoleSelected()) {
        for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("role_groupaware")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    emailusers = new TreeSet(selected); // convert List to Set (remove duplicates)

    m_subjectprefix = getSubjectPrefixFromConfig();

    EmailUser curUser = getCurrentUser();

    String fromEmail = "";
    String fromDisplay = "";
    if (curUser != null) {
        fromEmail = curUser.getEmail();
        fromDisplay = curUser.getDisplayname();
    }
    String fromString = fromDisplay + " <" + fromEmail + ">";

    m_results = "Message sent to: <br>";

    String subject = m_subject;

    //Should we append this to the archive?
    String emailarchive = "/mailarchive/channel/" + m_siteid + "/main";
    if (m_archiveMessage && isEmailArchiveInSite()) {
        String attachment_info = "<br/>";
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        int i = 0;
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            attachment_info += "<br/>";
            attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize()
                    + " Bytes)";
            i++;
        }
        this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info);
    }
    List headers = new ArrayList();
    if (getTextFormat().equals("htmltext"))
        headers.add("content-type: text/html");
    else
        headers.add("content-type: text/plain");

    String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
    //String smtp_port = ServerConfigurationService.getString("smtp.port");
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp_server);
        //props.put("mail.smtp.port", smtp_port);
        Session s = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(s);

        InternetAddress from = new InternetAddress(fromString);
        message.setFrom(from);
        String reply = getReplyToSelected().trim().toLowerCase();
        if (reply.equals("yes")) {
            // "reply to sender" is default. So do nothing
        } else if (reply.equals("no")) {
            String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">";
            InternetAddress noreplyemail = new InternetAddress(noreply);
            message.setFrom(noreplyemail);
        } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) {
            // need input(email) validation
            InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) };
            message.setReplyTo(replytoList);
        }
        message.setSubject(subject);
        String text = m_body;
        String attachmentdirectory = getUploadDirectory();

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        String messagetype = "";

        if (getTextFormat().equals("htmltext")) {
            messagetype = "text/html";
        } else {
            messagetype = "text/plain";
        }
        messageBodyPart.setContent(text, messagetype);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(
                    attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename());
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(a.getFilename());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);

        //Send the emails
        String recipientsString = "";
        for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") {
            EmailUser euser = (EmailUser) i.next();
            String toEmail = euser.getEmail(); // u.getEmail();
            String toDisplay = euser.getDisplayname(); // u.getDisplayName();
            // if AllUsers are selected, do not add current user's email to recipients
            if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) {
                // don't add sender to recipients
            } else {
                recipientsString += toEmail;
                m_results += toDisplay + (i.hasNext() ? "<br/>" : "");
            }
            //               InternetAddress to[] = {new InternetAddress(toEmail) };
            //               Transport.send(message,to);
        }
        if (m_otheremails.trim().equals("") != true) {
            //
            // multiple email validation is needed here
            //
            String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ',');
            recipientsString += refinedOtherEmailAddresses;
            m_results += "<br/>" + refinedOtherEmailAddresses;
            //               InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) };
            //               Transport.send(message, to);
        }
        if (m_sendmecopy) {
            message.addRecipients(Message.RecipientType.CC, fromEmail);
            // trying to solve SAK-7410
            // recipientsString+=fromEmail;
            //               InternetAddress to[] = {new InternetAddress(fromEmail) };
            //               Transport.send(message, to);
        }
        //            message.addRecipients(Message.RecipientType.TO, recipientsString);
        message.addRecipients(Message.RecipientType.BCC, recipientsString);

        Transport.send(message);
    } catch (Exception e) {
        log.debug("Mailtool Exception while trying to send the email: " + e.getMessage());
    }

    //   Clear the Subject and Body of the Message
    m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix();
    m_otheremails = "";
    m_body = "";
    num_files = 0;
    attachedFiles.clear();
    m_recipientSelector = null;
    m_recipientSelector1 = null;
    m_recipientSelector2 = null;
    m_recipientSelector3 = null;
    setAllUsersSelected(false);
    setAllGroupSelected(false);
    setAllSectionSelected(false);

    //  Display Users with Bad Emails if the option is turned on.
    boolean showBadEmails = getDisplayInvalidEmailAddr();
    if (showBadEmails == true) {
        m_results += "<br/><br/>";

        List /* String */ badnames = new ArrayList();

        for (Iterator i = selected.iterator(); i.hasNext();) {
            EmailUser user = (EmailUser) i.next();
            /* This check should maybe be some sort of regular expression */
            if (user.getEmail().equals("")) {
                badnames.add(user.getDisplayname());
            }
        }
        if (badnames.size() > 0) {
            m_results += "The following users do not have valid email addresses:<br/>";
            for (Iterator i = badnames.iterator(); i.hasNext();) {
                String name = (String) i.next();
                if (i.hasNext() == true)
                    m_results += name + "/ ";
                else
                    m_results += name;
            }
        }
    }
    return "results";
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

private MimeMessage prepareMimeMessage(MimeMessage mimeMessage, Node node, String template, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws AddressException, MessagingException, ValueFormatException,
        PathNotFoundException, RepositoryException, UnsupportedEncodingException {

    if (replyTo != null) {
        mimeMessage.setReplyTo(convertToInternetAddress(replyTo));
    } else {/*ww w. ja  v  a 2  s .co  m*/
        if (node != null && node.hasProperty("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(node.getProperty("replyTo").getString()));
        } else if (variables != null && variables.containsKey("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(variables.get("replyTo")));
        }
    }
    if (date == null) {
        if (node != null && node.hasProperty("mailDate")) {
            mimeMessage.setSentDate(node.getProperty("mailDate").getDate().getTime());
        } else if (variables != null && variables.containsKey("mailDate")) {
            mimeMessage.setSentDate((Date) variables.get("mailDate"));
        } else {
            mimeMessage.setSentDate(new Date());
        }
    } else {
        mimeMessage.setSentDate(date);
    }

    if (subject != null) {
        mimeMessage.setSubject(MimeUtility.encodeText(subject, configurator.getEncoding(), "Q"));
    } else {
        if (node != null && node.hasProperty("subject")) {
            mimeMessage.setSubject(MimeUtility.encodeText(node.getProperty("subject").getString(),
                    configurator.getEncoding(), "Q"));
        } else if (variables != null && variables.containsKey("subject")) {
            mimeMessage.setSubject(
                    MimeUtility.encodeText((String) variables.get("subject"), configurator.getEncoding(), "Q"));
        }
    }

    if (from != null) {
        mimeMessage.setFrom(convertToInternetAddress(from)[0]);
    } else {
        if (node != null && node.hasProperty("from")) {
            mimeMessage.setFrom(convertToInternetAddress(node.getProperty("from").getString())[0]);
        } else if (variables != null && variables.containsKey("from")) {
            mimeMessage.setFrom(convertToInternetAddress(variables.get("from"))[0]);
        }
    }

    if (to != null) {
        mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(to));
    } else {
        if (node != null && node.hasProperty("to")) {
            if (node.getProperty("to").isMultiple()) {
                Value[] values = node.getProperty("to").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.TO,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.TO,
                        convertToInternetAddress(node.getProperty("to").getString()));
            }
        } else if (variables != null && variables.containsKey("to")) {
            mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(variables.get("to")));
        }

    }

    if (cc != null) {
        mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(cc));
    } else {
        if (node != null && node.hasProperty("cc")) {
            if (node.getProperty("cc").isMultiple()) {
                Value[] values = node.getProperty("cc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.CC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.CC,
                        convertToInternetAddress(node.getProperty("cc").getString()));
            }
        } else if (variables != null && variables.containsKey("cc")) {
            mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(variables.get("cc")));
        }
    }

    if (bcc != null) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(bcc));
    } else {
        if (node != null && node.hasProperty("bcc")) {
            if (node.getProperty("bcc").isMultiple()) {
                Value[] values = node.getProperty("bcc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.BCC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.BCC,
                        convertToInternetAddress(node.getProperty("bcc").getString()));
            }
        } else if (variables != null && variables.containsKey("bcc")) {
            mimeMessage.addRecipients(Message.RecipientType.BCC,
                    convertToInternetAddress(variables.get("bcc")));
        }
    }
    return mimeMessage;
}