Example usage for javax.mail.internet MimeMessage setRecipients

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

Introduction

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

Prototype

public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Set the specified recipient type to the given addresses.

Usage

From source file:org.exjello.mail.Exchange2003Connection.java

public void send(MimeMessage message) throws Exception {
    Address[] bccRecipients = message.getRecipients(Message.RecipientType.BCC);
    if (bccRecipients == null || bccRecipients.length == 0) {
        bccRecipients = null;//from   w  w  w  .  j  a va 2s. co m
    }
    message.setRecipients(Message.RecipientType.BCC, (Address[]) null);
    synchronized (this) {
        if (!isConnected()) {
            throw new IllegalStateException("Not connected.");
        }
        if (!canSend()) {
            throw new IllegalStateException("Unable to access outbox.");
        }
        HttpClient client = getClient();
        String path = drafts;
        if (!path.endsWith("/"))
            path += "/";
        String messageName = generateMessageName();
        path += escape(messageName + ".eml");
        PutMethod op = new PutMethod(path);
        op.setRequestHeader("Content-Type", MESSAGE_CONTENT_TYPE);
        op.setRequestEntity(createMessageEntity(message));
        InputStream stream = null;
        try {
            int status = client.executeMethod(op);
            stream = op.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to post message to draft folder.");
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                op.releaseConnection();
            }
        }
        if (bccRecipients != null) {
            ExchangeMethod patch = new ExchangeMethod(PROPPATCH_METHOD, path);
            patch.setHeader("Content-Type", XML_CONTENT_TYPE);
            patch.addHeader("Depth", "0");
            patch.addHeader("Translate", "f");
            patch.addHeader("Brief", "t");
            patch.setRequestEntity(createAddBccEntity(bccRecipients));
            stream = null;
            try {
                int status = client.executeMethod(patch);
                stream = patch.getResponseBodyAsStream();
                if (status >= 300) {
                    throw new IllegalStateException("Unable to add BCC recipients. Status: " + status);
                }
            } finally {
                try {
                    if (stream != null) {
                        byte[] buf = new byte[65536];
                        try {
                            if (session.getDebug()) {
                                PrintStream log = session.getDebugOut();
                                log.println("Response Body:");
                                int count;
                                while ((count = stream.read(buf, 0, 65536)) != -1) {
                                    log.write(buf, 0, count);
                                }
                                log.flush();
                                log.println();
                            } else {
                                while (stream.read(buf, 0, 65536) != -1)
                                    ;
                            }
                        } catch (Exception ignore) {
                        } finally {
                            try {
                                stream.close();
                            } catch (Exception ignore2) {
                            }
                        }
                    }
                } finally {
                    patch.releaseConnection();
                }
            }
        }
        ExchangeMethod move = new ExchangeMethod(MOVE_METHOD, path);
        String destination = submissionUri;
        if (!destination.endsWith("/"))
            destination += "/";
        move.setHeader("Destination", destination);
        stream = null;
        try {
            int status = client.executeMethod(move);
            stream = move.getResponseBodyAsStream();
            if (status >= 300) {
                throw new IllegalStateException("Unable to move message to outbox: Status " + status);
            }
        } finally {
            try {
                if (stream != null) {
                    byte[] buf = new byte[65536];
                    try {
                        if (session.getDebug()) {
                            PrintStream log = session.getDebugOut();
                            log.println("Response Body:");
                            int count;
                            while ((count = stream.read(buf, 0, 65536)) != -1) {
                                log.write(buf, 0, count);
                            }
                            log.flush();
                            log.println();
                        } else {
                            while (stream.read(buf, 0, 65536) != -1)
                                ;
                        }
                    } catch (Exception ignore) {
                    } finally {
                        try {
                            stream.close();
                        } catch (Exception ignore2) {
                        }
                    }
                }
            } finally {
                move.releaseConnection();
            }
        }
        if (session.getDebug()) {
            session.getDebugOut().println("Sent successfully.");
        }
    }
}

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

protected void setRecipients(Map<RecipientType, InternetAddress[]> headerTo, MimeMessage msg)
        throws MessagingException {
    if (headerTo != null) {
        if (msg.getHeader(EmailHeaders.TO) == null && headerTo.containsKey(RecipientType.TO)) {
            msg.setRecipients(Message.RecipientType.TO, headerTo.get(RecipientType.TO));
        }/* w w w.jav  a 2 s. c  o  m*/
        if (msg.getHeader(EmailHeaders.CC) == null && headerTo.containsKey(RecipientType.CC)) {
            msg.setRecipients(Message.RecipientType.CC, headerTo.get(RecipientType.CC));
        }
        if (headerTo.containsKey(RecipientType.BCC)) {
            msg.setRecipients(Message.RecipientType.BCC, headerTo.get(RecipientType.BCC));
        }
    }
}

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.
 * /*from  w  w w.ja v  a  2  s  . com*/
 * @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:hudson.tasks.mail.impl.BaseBuildResultMail.java

/**
 * Creates empty mail./*ww w .  j a  v a2 s  . c o m*/
 *
 * @param build build.
 * @param listener listener.
 * @return empty mail.
 * @throws MessagingException exception if any.
 */
protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(getRecipients());
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address
            try {
                rcp.add(new InternetAddress(address));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    if (CollectionUtils.isNotEmpty(upstreamProjects)) {
        for (AbstractProject project : upstreamProjects) {
            includeCulpritsOf(project, build, listener, rcp);
        }
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail./*from w  w w  .j  a  v a2  s.  c o  m*/
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Create a mail.//from   w  ww  . j a va2s  .c  o  m
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null && Config.SEND_MAIL_FROM_USER) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/* ww w.  j  av  a 2 s .  c o m*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            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));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:hudson.tasks.MailSender.java

private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    msg.setContent("", "text/plain");
    msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset));
    msg.setSentDate(new Date());

    String replyTo = Mailer.descriptor().getReplyToAddress();
    if (StringUtils.isNotBlank(replyTo)) {
        msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) });
    }/*w  w  w.j  a  v  a  2s.  c  o  m*/

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    String defaultSuffix = Mailer.descriptor().getDefaultSuffix();
    StringTokenizer tokens = new StringTokenizer(recipients);
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Jenkins.getInstance().getItem(projectName, build.getProject(),
                    AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address

            // if not a valid address (i.e. no '@'), then try adding suffix
            if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) {
                address += defaultSuffix;
            }

            try {
                rcp.add(Mailer.StringToAddress(address, charset));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                listener.getLogger().println("Unable to send to address: " + address);
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    for (AbstractProject project : includeUpstreamCommitters) {
        includeCulpritsOf(project, build, listener, rcp);
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object/*from   w  ww  .j a  v a 2  s.c o  m*/
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();/*w  w  w .j av  a2 s.c o  m*/
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}