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

public void setSubject(String subject, String charset) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from  www  .ja v a  2s  .co m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:org.georchestra.console.mailservice.Email.java

protected void sendMsg(String msg) throws AddressException, MessagingException {

    if (LOG.isDebugEnabled()) {
        LOG.debug("body: " + msg);
    }//from w w w.  ja  v  a2  s. com

    // Replace {publicUrl} token with the configured public URL
    msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl"));

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", smtpHost);
    session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString());

    final MimeMessage message = new MimeMessage(session);

    if (isValidEmailAddress(from)) {
        message.setFrom(new InternetAddress(from));
    }
    boolean validRecipients = false;
    for (String recipient : recipients) {
        if (isValidEmailAddress(recipient)) {
            validRecipients = true;
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        }
    }

    if (!validRecipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(from));
        message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding);
    } else {
        message.setSubject(subject, subjectEncoding);
    }

    if (msg != null) {
        /* See http://www.rgagnon.com/javadetails/java-0321.html */
        if ("true".equalsIgnoreCase(emailHtml)) {
            message.setContent(msg, "text/html; charset=" + bodyEncoding);
        } else {
            message.setContent(msg, "text/plain; charset=" + bodyEncoding);
        }
        LOG.debug(msg);
    }

    Transport.send(message);
    LOG.debug("email has been sent to:\n" + Arrays.toString(recipients));
}

From source file:cc.kune.core.server.mail.MailServiceDefault.java

@Override
public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body,
        final boolean isHtml, final String... tos) {
    if (smtpSkip) {
        return;//from   www .  ja v  a2 s .co  m
    }

    // Get session
    final Session session = Session.getDefaultInstance(props, null);

    // Define message
    final MimeMessage message = new MimeMessage(session);
    for (final String to : tos) {
        try {
            message.setFrom(new InternetAddress(from));
            // In case we should use utf8 also in address:
            // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // If additional header should be added
            // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
            final String formatedSubject = subject.getString();
            message.setSubject(formatedSubject, "utf-8");
            final String formatedBody = body.getString();
            if (isHtml) {
                // message.setContent(formatedBody, "text/html");
                message.setText(formatedBody, "UTF-8", "html");
            } else {
                message.setText(formatedBody, "UTF-8");
            }
            // Send message
            Transport.send(message);
        } catch (final AddressException e) {
        } catch (final MessagingException e) {
            final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s",
                    from, subject, to);
            log.error(error, e);
            // Better not to throw exceptions because users emails can be wrong...
            // throw new DefaultException(error, e);
        }
    }
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

@Override
public Message sendMail(AppockMail appockMail) throws MessagingException {

    if (CollectionUtils.isEmpty(appockMail.getListeDestinataire())) {
        log.warn("Mail non envoy, liste des destinataires vide : " + appockMail);
        return null;
    }/*from  w  w w  . j  av a 2 s . c  o m*/

    MimeMessage msg = new MimeMessage(mailServer);
    msg.setFrom(appockMail.getFrom() != null ? appockMail.getFrom() : defaultFrom());

    String prefixeSujet = isModeProduction() ? "" : "[TEST APPOCK] ";
    msg.setSubject(prefixeSujet + appockMail.getSujet(), configService.getEncodageSujetEmail());

    StringBuilder infoAdditionnelle = new StringBuilder();

    for (InternetAddress adresse : appockMail.getListeDestinataire()) {
        if (isModeProduction()) {
            // on est en production, envoi rel de mail au destinataire
            msg.addRecipient(Message.RecipientType.TO, adresse);
        } else {
            // en test, on envoie le mail  la personne connecte
            InternetAddress adresseTesteur = getAdresseMailDestinataireTesteur();
            if (adresseTesteur != null) {
                msg.addRecipient(Message.RecipientType.TO, adresseTesteur);
            }
            List<String> listeAdresseMail = new ArrayList<>();
            for (InternetAddress internetAddress : appockMail.getListeDestinataire()) {
                listeAdresseMail.add(internetAddress.getAddress());
            }
            infoAdditionnelle.append("En production cet email serait envoy vers ")
                    .append(StringUtils.join(listeAdresseMail, ", ")).append("<br/><hr/>");
            break;
        }
    }

    String contenuFinal = "";
    if (!StringUtils.isBlank(infoAdditionnelle.toString())) {
        contenuFinal += "<font face=\"arial\" >" + infoAdditionnelle.toString() + "</font>";
    }

    contenuFinal += "<font face=\"arial\" >" + appockMail.getContenu() + "<br/><br/></font>"
            + configService.getPiedDeMail();

    gereBonLivraisonDansMail(appockMail, msg, contenuFinal);

    if (!ArrayUtils.isEmpty(msg.getAllRecipients())) {
        Transport.send(msg);
    }

    return msg;
}

From source file:org.projectforge.mail.SendMail.java

private void sendIt(final Mail composedMessage) {
    final Session session = Session.getInstance(properties);
    Transport transport = null;/*  w w w.  java2  s. c o  m*/
    try {
        MimeMessage message = new MimeMessage(session);
        if (composedMessage.getFrom() != null) {
            message.setFrom(new InternetAddress(composedMessage.getFrom()));
        } else {
            message.setFrom();
        }
        message.setRecipients(Message.RecipientType.TO, composedMessage.getTo());
        String subject;
        subject = composedMessage.getSubject();
        /*
         * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) {
         * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); }
         */
        message.setSubject(subject, sendMailConfig.getCharset());
        message.setSentDate(new Date());
        if (composedMessage.getContentType() != null) {
            message.setText(composedMessage.getContent(), composedMessage.getCharset(),
                    composedMessage.getContentType());
        } else {
            message.setText(composedMessage.getContent(), sendMailConfig.getCharset());
        }
        message.saveChanges(); // don't forget this
        transport = session.getTransport();
        if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) {
            transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException ex) {
        log.error("While creating and sending message: " + composedMessage.toString(), ex);
        throw new InternalErrorException("mail.error.exception");
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException ex) {
                log.error("While creating and sending message: " + composedMessage.toString(), ex);
                throw new InternalErrorException("mail.error.exception");
            }
        }
    }
    log.info("E-Mail successfully sent: " + composedMessage.toString());
}

From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java

/**
 * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME
 * format)./*from  w  w  w . j ava 2 s .  c  om*/
 *
 * @param pFrom : from field that will appear in the email header.
 * @param personalName :
 * @see {@link InternetAddress}
 * @param pTo : the email target destination.
 * @param pSubject : the subject of the email.
 * @param pMessage : the message or payload of the email.
 */
private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage,
        boolean htmlFormat) throws NotificationServerException {
    // retrieves system properties and set up Delivery Status Notification
    // @see RFC1891
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", getMailServer());
    properties.put("mail.smtp.auth", String.valueOf(isAuthenticated()));
    javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
    session.setDebug(isDebug()); // print on the console all SMTP messages.
    Transport transport = null;
    try {
        InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName);
        InternetAddress replyToAddress = null;
        InternetAddress[] toAddress = null;
        // parsing destination address for compliance with RFC822
        try {
            toAddress = InternetAddress.parse(pTo, false);
            if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom)
                    && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) {
                replyToAddress = new InternetAddress(pFrom, false);
                if (StringUtil.isDefined(personalName)) {
                    replyToAddress.setPersonal(personalName, CharEncoding.UTF_8);
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "From = " + pFrom + ", To = " + pTo);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        String subject = pSubject;
        if (subject == null) {
            subject = "";
        }
        String content = pMessage;
        if (content == null) {
            content = "";
        }
        email.setSubject(subject, CharEncoding.UTF_8);
        if (content.toLowerCase().contains("<html>") || htmlFormat) {
            email.setContent(content, "text/html; charset=\"UTF-8\"");
        } else {
            email.setText(content, CharEncoding.UTF_8);
        }
        email.setSentDate(new Date());

        // create a Transport connection (TCP)
        if (isSecure()) {
            transport = session.getTransport(SECURE_TRANSPORT);
        } else {
            transport = session.getTransport(SIMPLE_TRANSPORT);
        }
        if (isAuthenticated()) {
            SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin());
            transport.connect(getMailServer(), getPort(), getLogin(), getPassword());
        } else {
            transport.connect();
        }

        transport.sendMessage(email, toAddress);
    } catch (MessagingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR,
                "smtp.EX_CANT_SEND_SMTP_MESSAGE", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (Exception e) {
                SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e);
            }
        }
    }
}

From source file:nl.nn.adapterframework.senders.MailSenderOld.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection<Recipient> recipients,
        Collection<Attachment> attachments) throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from   www . ja v a  2 s .c o  m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Recipient recipient = (Recipient) iter.next();
            String value = recipient.value;
            String type = recipient.type;
            Message.RecipientType recipientType;
            if ("cc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.CC;
            } else if ("bcc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.BCC;
            } else {
                recipientType = Message.RecipientType.TO;
            }
            msg.addRecipient(recipientType, new InternetAddress(value));
            recipientsFound = true;
            if (log.isDebugEnabled()) {
                sb.append("[recipient [" + recipient + "]]");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            int counter = 0;
            iter = attachments.iterator();
            while (iter.hasNext()) {
                counter++;
                Attachment attachment = (Attachment) iter.next();
                Object value = attachment.getValue();
                String name = attachment.getName();
                if (StringUtils.isEmpty(name)) {
                    name = getDefaultAttachmentName() + counter;
                }
                log.debug("found attachment [" + attachment + "]");

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setFileName(name);

                if (value instanceof DataHandler) {
                    messageBodyPart.setDataHandler((DataHandler) value);
                } else {
                    messageBodyPart.setText((String) value);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private void applyMessageHeaders(final MimeMessage msg, Alert alert) throws MessagingException {
    String from = getSetting("from"), to = getSetting("to"), cc = getSetting("cc"), bcc = getSetting("bcc"),
            subject = getSubject(alert);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

    if ((cc != null) && (cc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
    }/*from   w w w .j av a2s.  c o m*/
    if ((bcc != null) && (bcc.trim().length() > 0)) {
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
    }

    if (subject != null) {
        msg.setSubject(subject, CharsetHelper.getEncoding());

    }

}

From source file:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*  w w w.j a v  a 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 {
    MimeMessage 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, "UTF-8");
    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
            Transport.send(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:org.snopoke.util.Emailer.java

/**
 * Create the MimeMessage and set the to/from/subject
 * /*from   w  w w.  j a va 2s.c  om*/
 * @return MimeMessaeg
 * @throws MessagingException
 */
private MimeMessage getMessasge() throws MessagingException {
    MimeMessage message = new MimeMessage(getSession());
    message.setSentDate(new Date());

    for (Address toAddress : to) {
        message.addRecipient(RecipientType.TO, toAddress.getInternetAddress());
    }

    for (Address toAddress : cc) {
        message.addRecipient(RecipientType.CC, toAddress.getInternetAddress());
    }

    for (Address toAddress : bcc) {
        message.addRecipient(RecipientType.BCC, toAddress.getInternetAddress());
    }

    message.setFrom(from.getInternetAddress());

    if (subject != null && !subject.isEmpty())
        message.setSubject(subject, "UTF-8");
    return message;
}