Example usage for javax.mail.internet InternetAddress setPersonal

List of usage examples for javax.mail.internet InternetAddress setPersonal

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress setPersonal.

Prototype

public void setPersonal(String name) throws UnsupportedEncodingException 

Source Link

Document

Set the personal name.

Usage

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email/*  w  w  w  .  j  a  v  a2  s  .  c o  m*/
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email/*from  ww w .ja  va 2s  .  c  o m*/
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());
    Session session = Session.getInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:org.hyperic.hq.bizapp.server.action.email.EmailAction.java

protected Map<EmailRecipient, AuthzSubject> lookupEmailAddr() throws ActionExecuteException {
    // First, look up the addresses
    HashSet<InternetAddress> prevRecipients = new HashSet<InternetAddress>();
    Map<EmailRecipient, AuthzSubject> validRecipients = new HashMap<EmailRecipient, AuthzSubject>();
    for (Iterator<?> it = getUsers().iterator(); it.hasNext();) {
        try {//  w w  w  . j ava  2  s .  co m
            InternetAddress addr;
            boolean useHtml = false;
            AuthzSubject who = null;
            switch (getType()) {
            case TYPE_USERS:
                Integer uid = (Integer) it.next();
                who = getSubjMan().getSubjectById(uid);
                if (who == null) {
                    _log.warn("User not found: " + uid);
                    continue;
                }
                addr = (isSms()) ? new InternetAddress(who.getSMSAddress())
                        : new InternetAddress(who.getEmailAddress());
                addr.setPersonal(who.getName());
                useHtml = isSms() ? false : who.isHtmlEmail();
                break;
            default:
            case TYPE_EMAILS:
                addr = new InternetAddress((String) it.next(), true);
                addr.setPersonal(addr.getAddress());
                break;
            }
            // Don't send duplicate notifications
            if (prevRecipients.add(addr)) {
                validRecipients.put(new EmailRecipient(addr, useHtml), who);
            }
        } catch (AddressException e) {
            _log.warn("Mail address invalid", e);
            continue;
        } catch (UnsupportedEncodingException e) {
            _log.warn("Username encoding error", e);
            continue;
        } catch (Exception e) {
            _log.warn("Email lookup failed");
            _log.debug("Email lookup failed", e);
            continue;
        }
    }
    return validRecipients;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * fix up From and ReplyTo if we need it to be from Postmaster
 *//*from   w  ww . j a va2  s .c om*/
private void checkFrom(MimeMessage msg) {

    String sendFromSakai = serverConfigurationService.getString(MAIL_SENDFROMSAKAI, "true");
    String sendExceptions = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_EXCEPTIONS, null);
    InternetAddress from = null;
    InternetAddress[] replyTo = null;

    try {
        Address[] fromA = msg.getFrom();
        if (fromA == null || fromA.length == 0) {
            M_log.info("message from missing");
            return;
        } else if (fromA.length > 1) {
            M_log.info("message from more than 1");
            return;
        } else if (fromA instanceof InternetAddress[]) {
            from = (InternetAddress) fromA[0];
        } else {
            M_log.info("message from not InternetAddress");
            return;
        }

        Address[] replyToA = msg.getReplyTo();
        if (replyToA == null)
            replyTo = null;
        else if (replyToA instanceof InternetAddress[])
            replyTo = (InternetAddress[]) replyToA;
        else {
            M_log.info("message replyto isn't internet address");
            return;
        }

        // should we replace from address with a Sakai address?
        if (sendFromSakai != null && !sendFromSakai.equalsIgnoreCase("false")) {
            // exceptions -- addresses to leave alone. Our own addresses are always exceptions.
            // you can also configure a regexp of exceptions.
            if (!from.getAddress().toLowerCase()
                    .endsWith("@" + serverConfigurationService.getServerName().toLowerCase())
                    && (sendExceptions == null || sendExceptions.equals("")
                            || !from.getAddress().toLowerCase().matches(sendExceptions))) {

                // not an exception. do the replacement.
                // First, decide on the replacement address. The config variable
                // may be the replacement address. If not, use postmaster
                if (sendFromSakai.indexOf("@") < 0)
                    sendFromSakai = POSTMASTER + "@" + serverConfigurationService.getServerName();

                // put the original from into reply-to, unless a replyto exists
                if (replyTo == null || replyTo.length == 0 || replyTo[0].getAddress().equals("")) {
                    replyTo = new InternetAddress[1];
                    replyTo[0] = from;
                    msg.setReplyTo(replyTo);
                }
                // for some reason setReplyTo doesn't work, though setFrom does. Have to create the
                // actual header line
                if (msg.getHeader(EmailHeaders.REPLY_TO) == null)
                    msg.addHeader(EmailHeaders.REPLY_TO, from.getAddress());

                // and use the new from address
                // biggest issue is the "personal address", i.e. the comment text

                String origFromText = from.getPersonal();
                String origFromAddress = from.getAddress();
                String fromTextPattern = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_FROMTEXT,
                        "{}");

                String fromText = null;
                if (origFromText != null && !origFromText.equals(""))
                    fromText = fromTextPattern.replace("{}", origFromText + " (" + origFromAddress + ")");
                else
                    fromText = fromTextPattern.replace("{}", origFromAddress);

                from = new InternetAddress(sendFromSakai);
                try {
                    from.setPersonal(fromText);
                } catch (Exception e) {
                }

                msg.setFrom(from);
            }
        }
    } catch (javax.mail.internet.AddressException e) {
        M_log.info("checkfrom address exception " + e);
    } catch (javax.mail.MessagingException e) {
        M_log.info("checkfrom messaging exception " + e);
    }

}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * {@inheritDoc}/*from   w  w w  .  ja v  a2  s . c  o  m*/
 * 
 * @see org.sakaiproject.email.api.EmailService#send(EmailMessage)
 */
public List<EmailAddress> send(EmailMessage msg, boolean messagingException)
        throws AddressValidationException, NoRecipientsException, MessagingException {
    ArrayList<EmailAddress> invalids = new ArrayList<EmailAddress>();

    InternetAddress from = null;
    // convert and validate the 'from' address
    try {
        from = new InternetAddress(msg.getFrom().getAddress(), true);
        from.setPersonal(msg.getFrom().getPersonal());
    } catch (AddressException e) {
        throw new AddressValidationException("Invalid 'FROM' address: " + msg.getFrom().getAddress(),
                msg.getFrom());
    } catch (UnsupportedEncodingException e) {
        throw new AddressValidationException("Invalid 'FROM' address: " + msg.getFrom().getAddress(),
                msg.getFrom());
    }

    // convert and validate reply to addresses
    InternetAddress[] replyTo = emails2Internets(msg.getReplyTo(), invalids);
    if (!invalids.isEmpty()) {
        throw new AddressValidationException("Invalid 'REPLY TO' address", invalids);
    }

    /*
     * LOOK - IF THERE ARE ANY INVALID RECIPIENT, AN EXCEPTION IS THROWN AND THE METHOD EXITS
     */
    // convert and validate the 'to' addresses
    InternetAddress[] to = emails2Internets(msg.getRecipients(RecipientType.TO), invalids);

    // convert and validate 'cc' addresses
    InternetAddress[] cc = emails2Internets(msg.getRecipients(RecipientType.CC), invalids);

    // convert and validate 'bcc' addresses
    InternetAddress[] bcc = emails2Internets(msg.getRecipients(RecipientType.BCC), invalids);

    // convert and validate actual email addresses
    InternetAddress[] actual = emails2Internets(msg.getRecipients(RecipientType.ACTUAL), invalids);

    // check that some actual addresses were given. if not, use a compilation of to, cc, bcc
    if (actual.length == 0) {
        int total = to.length + cc.length + bcc.length;
        if (total == 0) {
            throw new NoRecipientsException(
                    "No valid recipients found on message.  Check for invalid email addresses returned from this method.");
        }

        actual = new InternetAddress[total];
        int count = 0;
        for (InternetAddress t : to) {
            actual[count++] = t;
        }
        for (InternetAddress c : cc) {
            actual[count++] = c;
        }
        for (InternetAddress b : bcc) {
            actual[count++] = b;
        }
    }

    // rebundle addresses to expected param type
    HashMap<RecipientType, InternetAddress[]> headerTo = new HashMap<RecipientType, InternetAddress[]>();
    headerTo.put(RecipientType.TO, to);
    headerTo.put(RecipientType.CC, cc);
    headerTo.put(RecipientType.BCC, bcc);

    // convert headers to expected format
    List<String> headers = msg.extractHeaders();

    // build the content type
    String contentType = EmailHeaders.CONTENT_TYPE + ": " + msg.getContentType();
    if (msg.getCharacterSet() != null && msg.getCharacterSet().trim().length() != 0) {
        contentType += "; charset=" + msg.getCharacterSet();
    }
    // message format is only used when content type is text/plain as specified in the rfc
    if (ContentType.TEXT_PLAIN.equals(msg.getCharacterSet()) && msg.getFormat() != null
            && msg.getFormat().trim().length() != 0) {
        contentType += "; format=" + msg.getFormat();
    }
    // add the content type to the headers
    headers.add(contentType);

    // send the message
    try {
        sendMailMessagingException(from, actual, msg.getSubject(), msg.getBody(), headerTo, replyTo, headers,
                msg.getAttachments());
    } catch (MessagingException e) {
        // Just log it, if user doesn't want it thrown
        if (messagingException == false) {
            M_log.error("Email.sendMail: exception: " + e.getMessage(), e);
        } else {
            throw e;
        }
    }
    return invalids;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

/**
 * Converts a {@link java.util.List} of {@link EmailAddress} to
 * {@link javax.mail.internet.InternetAddress}.
 *
 * @param emails/*from w w w  .ja v  a2  s .  c  o  m*/
 * @return Array will be the same size as the list with converted addresses. If list is null,
 *         the array returned will be 0 length (non-null).
 * @throws AddressException
 * @throws UnsupportedEncodingException
 */
protected InternetAddress[] emails2Internets(List<EmailAddress> emails, List<EmailAddress> invalids) {
    // set the default return value
    InternetAddress[] addrs = new InternetAddress[0];

    if (emails != null && !emails.isEmpty()) {
        ArrayList<InternetAddress> laddrs = new ArrayList<InternetAddress>();
        for (int i = 0; i < emails.size(); i++) {
            EmailAddress email = emails.get(i);
            try {
                InternetAddress ia = new InternetAddress(email.getAddress(), true);
                ia.setPersonal(email.getPersonal());
                laddrs.add(ia);
            } catch (AddressException e) {
                invalids.add(email);
            } catch (UnsupportedEncodingException e) {
                invalids.add(email);
            }
        }
        if (!laddrs.isEmpty()) {
            addrs = laddrs.toArray(addrs);
        }
    }

    return addrs;
}

From source file:org.tsm.concharto.web.util.ConfirmationEmail.java

public static MimeMessage makeMessage(MimeMessage message, User user, String subject, String messageText) {
    InternetAddress from = new InternetAddress();
    from.setAddress(FROM_ADDRESS);/*w w w.jav  a2s  . co  m*/
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal(FROM_NAME);
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(subject);
        message.setText(messageText);
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}

From source file:org.xcolab.portlets.massmessaging.action.EditMessagingMessageAction.java

public void processAction(ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
        ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    String name = ParamUtil.getString(actionRequest, "name");
    String description = ParamUtil.getString(actionRequest, "description");
    String replyTo = ParamUtil.getString(actionRequest, "replyto");
    String subject = ParamUtil.getString(actionRequest, "subject");
    String body = ParamUtil.getString(actionRequest, "body");
    String recipientsStr = ParamUtil.getString(actionRequest, "recipients");
    String messageSenderName = ParamUtil.getString(actionRequest, "messageSenderName");
    boolean sendToAll = ParamUtil.getBoolean(actionRequest, "sendtoall");

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    Long companyId = themeDisplay.getCompanyId();

    if (isNullOrEmpty(name) || isNullOrEmpty(replyTo) || isNullOrEmpty(subject) || isNullOrEmpty(body)) {
        SessionErrors.add(actionRequest, "Input validation error");
    }//from w  w w  .ja  v  a2  s .  c  om

    // get ignored recipients 
    List<MessagingIgnoredRecipients> ignoredRecipients = MessagingIgnoredRecipientsLocalServiceUtil
            .getMessagingIgnoredRecipientses(0, Integer.MAX_VALUE);

    Set<String> doNotSendSet = new HashSet<String>();

    for (MessagingIgnoredRecipients recipient : ignoredRecipients) {
        doNotSendSet.add(recipient.getEmail());
        if (recipient.getName() != null) {
            doNotSendSet.add(recipient.getName());
        }
    }

    // validate recipients
    String[] recipientsArray = recipientsStr.split(MessagingConstants.RECIPIENT_DELIMITER);
    List<MessagingMessageRecipient> recipients = new ArrayList<MessagingMessageRecipient>();
    try {
        for (String recipientName : recipientsArray) {
            if (doNotSendSet.contains(recipientName)) {
                continue;
            }

            if (recipientName.trim().equals("")) {
                continue;
            }

            Long recipientId = CounterLocalServiceUtil.increment(MessagingMessageRecipient.class.getName());
            MessagingMessageRecipient msgRecipient = MessagingMessageRecipientLocalServiceUtil
                    .createMessagingMessageRecipient(recipientId);

            if (recipientName.lastIndexOf('@') > 0) {
                // we have an email
                if (!recipientName.matches(emailValidationRegexp)) {
                    throw new InvalidMessageRecipientException("Provided email is invalid: " + recipientName);
                }
                msgRecipient.setEmailAddress(recipientName);
            } else if (!sendToAll) {
                try {
                    User user = UserLocalServiceUtil.getUserByScreenName(companyId, recipientName);
                    if (!doNotSendSet.contains(user.getEmailAddress())
                            && !doNotSendSet.contains(user.getScreenName())) {
                        msgRecipient.setUserId(user.getUserId());
                        msgRecipient.setEmailAddress(user.getEmailAddress());
                    }
                } catch (NoSuchUserException e) {
                    throw new InvalidMessageRecipientException(
                            "User with screen name: " + recipientName + " doesn't exist", e);
                }
            }
            recipients.add(msgRecipient);
        }
    } catch (Exception e) {
        if (e instanceof InvalidMessageRecipientException) {
            SessionErrors.add(actionRequest, e.getClass().getName());
        }
        return;
    }
    if (recipients.size() == 0 && !sendToAll) {
        SessionErrors.add(actionRequest, "No recipients given.");
        return;
    }

    // validation complete save 

    Date now = new Date();

    Long messageId = CounterLocalServiceUtil.increment(MessagingMessage.class.getName());
    MessagingMessage message = MessagingMessageLocalServiceUtil.createMessagingMessage(messageId);

    StringBuilder messageBody = new StringBuilder();

    // rewrite all links to track if they are clicked
    Matcher linkMatcher = linkSearchRegexp.matcher(body);
    StringBuilder modifiedBody = new StringBuilder();
    int lastAppendIndex = 0;

    Map<String, String> linkParameters = new HashMap<String, String>();
    linkParameters.put(MessagingConstants.PARAMETER_ACTION, MessagingConstants.ACTION_REDIRECT);
    linkParameters.put(MessagingConstants.PARAMETER_MESSAGE_ID, String.valueOf(messageId));

    while (linkMatcher.find()) {

        int linkEndIndex = body.indexOf('"', linkMatcher.end() + 1);

        String linkURL = body.substring(linkMatcher.end(), linkEndIndex);

        Long redirectId = CounterLocalServiceUtil.increment(MessagingRedirectLink.class.getName());
        MessagingRedirectLink redirectLink = MessagingRedirectLinkLocalServiceUtil
                .createMessagingRedirectLink(redirectId);

        redirectLink.setLink(linkURL);
        redirectLink.setCreateDate(now);
        redirectLink.setMessageId(messageId);

        MessagingRedirectLinkLocalServiceUtil.addMessagingRedirectLink(redirectLink);

        linkParameters.put(MessagingConstants.PARAMETER_REDIRECT_ID, String.valueOf(redirectId));
        linkParameters.put(MessagingConstants.PARAMETER_RECIPIENT_ID,
                MessagingConstants.RECIPIENT_ID_PLACEHOLDER);

        String newLink = MessagingUtils.createConvertionLink(linkParameters, actionRequest);

        modifiedBody.append(body.substring(lastAppendIndex, linkMatcher.end()));
        modifiedBody.append(newLink);

        lastAppendIndex = linkEndIndex;
    }

    modifiedBody.append(body.substring(lastAppendIndex));

    // add link to image to trace mail opening
    linkParameters.clear();
    linkParameters.put(MessagingConstants.PARAMETER_ACTION, MessagingConstants.ACTION_IMAGE);
    linkParameters.put(MessagingConstants.PARAMETER_MESSAGE_ID, String.valueOf(messageId));

    String imgStr = " <img src=\"" + MessagingUtils.createConvertionLink(linkParameters, actionRequest)
            + "\" />";

    messageBody.append(HTML_HEADER);
    messageBody.append(modifiedBody);
    messageBody.append(imgStr);
    messageBody.append(HTML_FOOTER);

    body = messageBody.toString();

    if (sendToAll) {
        List<User> users = UserLocalServiceUtil.getUsers(0, UserLocalServiceUtil.getUsersCount());
        for (User user : users) {
            if (!isNullOrEmpty(user.getEmailAddress()) && !doNotSendSet.contains(user.getScreenName())
                    && !doNotSendSet.contains(user.getEmailAddress())) {

                Long recipientId = CounterLocalServiceUtil.increment(MessagingMessageRecipient.class.getName());
                MessagingMessageRecipient msgRecipient = MessagingMessageRecipientLocalServiceUtil
                        .createMessagingMessageRecipient(recipientId);

                msgRecipient.setEmailAddress(user.getEmailAddress());
                msgRecipient.setUserId(user.getUserId());
                recipients.add(msgRecipient);
            }
        }
    }

    if (recipients.size() == 0) {
        SessionErrors.add(actionRequest, "No recipients given.");
        return;
    }

    // save all recipients
    for (MessagingMessageRecipient rec : recipients) {
        rec.setMessageId(messageId);
        MessagingMessageRecipientLocalServiceUtil.addMessagingMessageRecipient(rec);
    }

    message.setName(name);
    message.setDescription(description);
    message.setReplyTo(replyTo);
    message.setSubject(subject);
    message.setBody(body.replaceAll(MessagingConstants.RECIPIENT_ID_PLACEHOLDER,
            String.valueOf(recipients.get(0).getRecipientId())));
    message.setConversionCount(0L);

    message.setCreatorId(themeDisplay.getUserId());
    message.setCreateDate(now);
    message.setModifiedDate(now);
    message.setSendToAll(sendToAll);

    MessagingMessageLocalServiceUtil.addMessagingMessage(message);

    InternetAddress from = new InternetAddress(replyTo);
    if (!isNullOrEmpty(messageSenderName)) {
        from.setPersonal(messageSenderName);
    }
    for (MessagingMessageRecipient rec : recipients) {
        InternetAddress to = new InternetAddress(rec.getEmailAddress());
        MailEngine.send(from, to, subject, body.replaceAll(MessagingConstants.RECIPIENT_ID_PLACEHOLDER,
                String.valueOf(rec.getRecipientId())), true);
    }

    SessionMessages.add(actionRequest, "Message was sent");
    actionResponse.sendRedirect(MessagingConstants.VIEW_MESSAGE_DETAILS + messageId);

}