Example usage for javax.mail.internet MimeBodyPart setDataHandler

List of usage examples for javax.mail.internet MimeBodyPart setDataHandler

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart setDataHandler.

Prototype

@Override
public void setDataHandler(DataHandler dh) throws MessagingException 

Source Link

Document

This method provides the mechanism to set this body part's content.

Usage

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

private void addFormMultipart(HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value)
        throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();

    if (value.startsWith("file:")) {
        String fileName = value.substring(5);
        File file = new File(fileName);
        part.setDisposition("form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"");
        if (file.exists()) {
            part.setDataHandler(new DataHandler(new FileDataSource(file)));
        } else {/*  w w  w.  ja  v a2 s.  c  o  m*/
            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getName().equals(fileName)) {
                    part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));
                    break;
                }
            }
        }

        part.setHeader("Content-Type", ContentTypeHandler.getContentTypeFromFilename(file.getName()));
        part.setHeader("Content-Transfer-Encoding", "binary");
    } else {
        part.setDisposition("form-data; name=\"" + name + "\"");
        part.setText(value, System.getProperty("soapui.request.encoding", request.getEncoding()));
    }

    if (part != null) {
        formMp.addBodyPart(part);
    }
}

From source file:immf.MyHtmlEmail.java

/**
 * Embeds the specified <code>DataSource</code> in the HTML using the
 * specified Content-ID. Returns the specified Content-ID string.
 *
 * @param dataSource the <code>DataSource</code> to embed
 * @param name the name that will be set in the filename header field
 * @param cid the Content-ID to use for this <code>DataSource</code>
 * @return the supplied Content-ID for this <code>DataSource</code>
 * @throws EmailException if the embedding fails or if <code>name</code> is
 * null or empty//from w w w .j  a v  a  2  s.c o m
 * @since 1.1
 */
public String embed(DataSource dataSource, String name, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:immf.MyHtmlEmail.java

public String embed(DataSource dataSource, String name, String nameCharset, String cid) throws EmailException {
    if (StringUtils.isEmpty(name)) {
        throw new EmailException("name cannot be null or empty");
    }/* w w  w  . j ava  2 s  . c  om*/

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(dataSource));
        Util.setFileName(mbp, name, nameCharset, null);
        //mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.setContentID("<" + cid + ">");

        InlineImage ii = new InlineImage(cid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return cid;
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

private void initRootPart(String requestContent, MimeMultipart mp, boolean isXOP) throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart("8bit");
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);/*from  w w w .  j  a  v a  2s  . com*/

    DataHandler dataHandler = new DataHandler(new MockResponseDataSource(this, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: inline
 *
 * @param file/*w  ww  . j ava 2 s  .  com*/
 *            ?
 * @return MimeBodyPartContent-Disposition: inline?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createImagePart(InlineImageFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart imagePart = new MimeBodyPart();
    imagePart.setContentID(file.getContentId());
    imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    imagePart.setDataHandler(new DataHandler(file.getDataSource()));
    imagePart.setDisposition(MimeBodyPart.INLINE);
    return imagePart;
}

From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java

private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(attachment.getName());
    if (StringUtils.isNotBlank(attachment.getDescription())) {
        attachmentPart.setDescription(attachment.getDescription());
    }// www  .j a v a2s .c  o  m
    if (StringUtils.isNotBlank(attachment.getDisposition())) {
        attachmentPart.setDisposition(attachment.getDisposition());
    }
    DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType());
    attachmentPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachmentPart);
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;/*w  w  w .j  a  v a 2  s  . co  m*/
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body)
        throws IOException, MessagingException {

    if (index == 0 && !StringUtils.isEmpty(headerNote))
        body.append(headerNote);/*from   www .j  av  a  2 s. c o m*/

    numberFormatter.setMaximumFractionDigits(1);
    numberFormatter.setMinimumFractionDigits(1);

    File file = createImage(appGroup);

    if (file == null)
        return null;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
            end);
    body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link,
            appGroup.getDisplayName()));

    body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">");
    body.append(
            "<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>");
    for (int i = 0; i <= accounts.size(); i++) {
        int cols = i == accounts.size() ? 1 : regions.size();
        String accName = i == accounts.size() ? "total" : accounts.get(i).name;
        body.append(String.format(
                "<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols))
                .append(accName).append("</td>");
    }
    body.append("</tr>");
    body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>");
    for (int i = 0; i < accounts.size(); i++) {
        boolean first = true;
        for (Region region : regions) {
            body.append("<td style=\"font-weight: bold;padding: 4px;"
                    + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name)
                    .append("</td>");
            first = false;
        }
    }
    body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>");

    Map<String, Double> costs = Maps.newHashMap();

    Interval interval = new Interval(end.minusWeeks(numWeeks), end);
    double[] total = new double[numWeeks];
    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        for (int i = 0; i < accounts.size(); i++) {
            List<Account> accountList = Lists.newArrayList(accounts.get(i));
            TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null,
                    null, resourceGroups);
            Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region,
                    AggregateType.none, false);
            for (Tag tag : data.keySet()) {
                for (int week = 0; week < numWeeks; week++) {
                    String key = accounts.get(i) + "|" + tag + "|" + week;
                    if (costs.containsKey(key))
                        costs.put(key, data.get(tag)[week] + costs.get(key));
                    else
                        costs.put(key, data.get(tag)[week]);
                    total[week] += data.get(tag)[week];
                }
            }
        }
    }

    boolean firstLine = true;
    DateTime currentWeekEnd = end;
    for (int week = numWeeks - 1; week >= 0; week--) {
        String weekStr;
        if (week == numWeeks - 1)
            weekStr = "Last week";
        else
            weekStr = (numWeeks - week - 1) + " weeks ago";
        String background = week % 2 == 1 ? "background: whiteSmoke;" : "";
        body.append(String.format(
                "<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>",
                background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5),
                formatter.print(currentWeekEnd).substring(5)));
        for (int i = 0; i < accounts.size(); i++) {
            Account account = accounts.get(i);
            for (int j = 0; j < regions.size(); j++) {
                Region region = regions.get(j);
                String key = account + "|" + region + "|" + week;
                double cost = costs.get(key) == null ? 0 : costs.get(key);
                Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1));
                link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account),
                        Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd);
                body.append(getValueCell(cost, lastCost, link, firstLine));
            }
        }
        link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions,
                currentWeekEnd.minusWeeks(1), currentWeekEnd);
        body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine));
        body.append("</tr>");
        firstLine = false;
        currentWeekEnd = currentWeekEnd.minusWeeks(1);
    }
    body.append("</table>");

    numberFormatter.setMaximumFractionDigits(0);
    numberFormatter.setMinimumFractionDigits(0);

    if (!StringUtils.isEmpty(throughputMetrics))
        body.append(throughputMetrics);

    body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>");
    for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) {
        String product = entry.getKey();
        List<String> selected = entry.getValue();
        if (selected == null || selected.size() == 0)
            continue;
        link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
                end);
        body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>",
                getResourceGroupsDisplayName(product), link, appGroup.getDisplayName()));
        for (String name : selected)
            body.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").append(name).append("<br>");
    }
    body.append("<hr><br>");

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setFileName(file.getName());
    DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png");
    mimeBodyPart.setDataHandler(new DataHandler(ds));
    mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">");
    mimeBodyPart.setHeader("Content-Disposition", "inline");
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);

    file.delete();

    return mimeBodyPart;
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String send() {
    List attachmentList = null;//  ww w .ja va2s  .c  o m
    AttachmentData a = null;
    try {
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        Session session;
        session = Session.getInstance(props);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);
        InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) };
        msg.setRecipients(Message.RecipientType.TO, toIA);

        if ("yes".equals(ccMe)) {
            InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) };
            msg.setRecipients(Message.RecipientType.CC, ccIA);
        }
        msg.setSubject(subject);

        EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email");
        attachmentList = emailBean.getAttachmentList();
        StringBuilder content = new StringBuilder(message);
        ArrayList fileList = new ArrayList();
        ArrayList fileNameList = new ArrayList();
        if (attachmentList != null) {
            if (prefixedPath == null || prefixedPath.equals("")) {
                log.error("samigo.email.prefixedPath is not set");
                return "error";
            }
            Iterator iter = attachmentList.iterator();
            while (iter.hasNext()) {
                a = (AttachmentData) iter.next();
                if (a.getIsLink().booleanValue()) {
                    log.debug("send(): url");
                    content.append("<br/>\n\r");
                    content.append("<br/>"); // give a new line
                    content.append(a.getFilename());
                } else {
                    log.debug("send(): file");
                    File attachedFile = getAttachedFile(a.getResourceId());
                    fileList.add(attachedFile);
                    fileNameList.add(a.getFilename());
                }
            }
        }

        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html");
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

        for (int i = 0; i < fileList.size(); i++) {
            messageBodyPart = new MimeBodyPart();
            FileDataSource source = new FileDataSource((File) fileList.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName((String) fileNameList.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);

        Transport.send(msg);
    } catch (UnsupportedEncodingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (MessagingException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (ServerOverloadException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (PermissionException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IdUnusedException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (TypeException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } catch (IOException e) {
        log.error("Exception throws from send()" + e.getMessage());
        return "error";
    } finally {
        if (attachmentList != null) {
            if (prefixedPath != null && !prefixedPath.equals("")) {
                StringBuilder sbPrefixedPath;
                Iterator iter = attachmentList.iterator();
                while (iter.hasNext()) {
                    sbPrefixedPath = new StringBuilder(prefixedPath);
                    sbPrefixedPath.append("/email_tmp/");
                    a = (AttachmentData) iter.next();
                    if (!a.getIsLink().booleanValue()) {
                        deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString());
                    }
                }
            }
        }
    }
    return "send";
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * //from ww  w.  j av a  2  s.co m
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    String name = attachment.getFilename();
    byte[] stream = attachment.getContent();
    File temp = File.createTempFile("tmpfile", ".tmp");
    FileOutputStream fos = new FileOutputStream(temp);
    fos.write(stream);
    fos.close();
    DataSource source = new FileDataSource(temp);
    MimeBodyPart part = new MimeBodyPart();
    String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

    part.setDataHandler(new DataHandler(source));
    part.setHeader("Content-Type", mimeType);
    part.setFileName(name);
    part.setContentID("<" + name + ">");
    part.setDisposition("inline");

    temp.deleteOnExit();

    return part;
}