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:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody/*from   ww  w  .ja  v a2s . c o  m*/
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            if (mimeType.equals("text/plain")) {
                mimeType = MimeType.DEFAULT;
            }
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param file     The file.//  w  ww.  jav a  2 s. c  om
 * @param contentType The Mime content type of the file.
 * @param fileName The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final File file, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(file) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param pathToFile The complete path to the file - including file name.
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart./*from w  w  w. ja  va 2 s.  c  o m*/
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final String pathToFile, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(pathToFile) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

public static MimeMessage createReport(final MailDefinition mailDefinition, final Session session,
        final DataRow parameters) throws ReportProcessingException, ContentIOException, MessagingException {
    final MasterReport bodyReport = mailDefinition.getBodyReport();
    final String[] paramNames = parameters.getColumnNames();
    final ReportParameterValues parameterValues = bodyReport.getParameterValues();
    for (int i = 0; i < paramNames.length; i++) {
        final String paramName = paramNames[i];
        if (isParameterDefined(bodyReport, paramName)) {
            parameterValues.put(paramName, parameters.get(paramName));
        }/*from   w  w w .ja  va 2  s . c om*/
    }

    final ReportProcessTaskRegistry registry = ReportProcessTaskRegistry.getInstance();
    final String bodyType = mailDefinition.getBodyType();
    final ReportProcessTask processTask = registry.createProcessTask(bodyType);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ReportProcessTaskUtil.configureBodyStream(processTask, bout, "report", null);
    processTask.setReport(bodyReport);
    if (processTask instanceof MultiStreamReportProcessTask) {
        final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) processTask;
        mtask.setBulkLocation(mtask.getBodyContentLocation());
        mtask.setBulkNameGenerator(new DefaultNameGenerator(mtask.getBodyContentLocation(), "data"));
        mtask.setUrlRewriter(new MailURLRewriter());
    }
    processTask.run();
    if (processTask.isTaskSuccessful() == false) {
        if (processTask.isTaskAborted()) {
            logger.info("EMail Task received interrupt.");
            return null;
        } else {
            logger.info("EMail Task failed:", processTask.getError());
            throw new ReportProcessingException("EMail Task failed", processTask.getError());
        }
    }

    final EmailRepository repository = new EmailRepository(session);
    final MimeBodyPart messageBodyPart = repository.getBodypart();
    final ByteArrayDataSource dataSource = new ByteArrayDataSource(bout.toByteArray(),
            processTask.getReportMimeType());
    messageBodyPart.setDataHandler(new DataHandler(dataSource));

    final int attachmentsSize = mailDefinition.getAttachmentCount();
    for (int i = 0; i < attachmentsSize; i++) {
        final MasterReport report = mailDefinition.getAttachmentReport(i);
        final String type = mailDefinition.getAttachmentType(i);
        final ContentLocation location = repository.getRoot();
        final ContentLocation bulkLocation = location.createLocation("attachment-" + i);

        final ReportProcessTask attachmentProcessTask = registry.createProcessTask(type);
        attachmentProcessTask.setBodyContentLocation(bulkLocation);
        attachmentProcessTask.setBodyNameGenerator(new DefaultNameGenerator(bulkLocation, "report"));
        attachmentProcessTask.setReport(report);
        if (attachmentProcessTask instanceof MultiStreamReportProcessTask) {
            final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) attachmentProcessTask;
            mtask.setBulkLocation(bulkLocation);
            mtask.setBulkNameGenerator(new DefaultNameGenerator(bulkLocation, "data"));
            mtask.setUrlRewriter(new MailURLRewriter());
        }
        attachmentProcessTask.run();

        if (attachmentProcessTask.isTaskSuccessful() == false) {
            if (attachmentProcessTask.isTaskAborted()) {
                logger.info("EMail Task received interrupt.");
            } else {
                logger.info("EMail Task failed:", attachmentProcessTask.getError());
                throw new ReportProcessingException("EMail Task failed", attachmentProcessTask.getError());
            }
        }
    }

    return repository.getEmail();
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param data Data/*from  w ww .java  2 s.c  o m*/
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromData(byte[] data, final String contentType, String fileName)
        throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        ByteArrayDataSource dataSource = new ByteArrayDataSource(data, contentType) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(dataSource));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra data[]", e);
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a simple MimeBodyPart from an attachment
 *///from w w  w  . j  a v  a2 s  .  co m

public static void addSingleAttachment(MimeMultipart mp, StringToStringMap contentIds, Attachment att)
        throws MessagingException {
    String contentType = att.getContentType();
    MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
            : new PreencodedMimeBodyPart("binary");

    part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
    initPartContentId(contentIds, part, att, false);

    mp.addBodyPart(part);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a mulitpart MimeBodyPart from an array of attachments
 *//*from  w  ww  . ja  va 2s .c  o  m*/

public static void addMultipartAttachment(MimeMultipart mp, StringToStringMap contentIds,
        List<Attachment> attachments) throws MessagingException {
    MimeMultipart multipart = new MimeMultipart("mixed");
    long totalSize = 0;

    for (int c = 0; c < attachments.size(); c++) {
        Attachment att = attachments.get(c);
        String contentType = att.getContentType();
        totalSize += att.getSize();

        MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
                : new PreencodedMimeBodyPart("binary");

        part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
        initPartContentId(contentIds, part, att, false);
        multipart.addBodyPart(part);
    }

    MimeBodyPart part = new PreencodedMimeBodyPart("binary");

    if (totalSize > MAX_SIZE_IN_MEMORY_ATTACHMENT) {
        part.setDataHandler(new DataHandler(new MultipartAttachmentFileDataSource(multipart)));
    } else {
        part.setDataHandler(new DataHandler(new MultipartAttachmentDataSource(multipart)));
    }

    Attachment attachment = attachments.get(0);
    initPartContentId(contentIds, part, attachment, true);

    mp.addBodyPart(part);
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//  w ww.ja  v  a 2  s. co m
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

public static boolean prepareMessagePart(WsdlAttachmentContainer container, MimeMultipart mp,
        MessageXmlPart messagePart, StringToStringMap contentIds) throws Exception, MessagingException {
    boolean isXop = false;

    XmlObjectTreeModel treeModel = null;
    XmlCursor cursor = messagePart.newCursor();
    XmlObject rootXmlObject = cursor.getObject();

    try {/*from   w w w  .ja  v a  2  s  .com*/
        while (!cursor.isEnddoc()) {
            if (cursor.isContainer()) {
                // could be an attachment part (as of "old" SwA specs which
                // specify a content
                // element referring to the attachment)
                if (messagePart.isAttachmentPart()) {
                    String href = cursor.getAttributeText(XOP_HREF_QNAME);
                    if (href != null && href.length() > 0) {
                        contentIds.put(messagePart.getPart().getName(), href);
                    }

                    break;
                }

                XmlObject xmlObj = cursor.getObject();
                SchemaType schemaType = xmlObj.schemaType();
                if (schemaType.isNoType()) {
                    if (treeModel == null) {
                        treeModel = new XmlObjectTreeModel(messagePart.getSchemaType().getTypeSystem(),
                                rootXmlObject);
                    }

                    XmlTreeNode tn = treeModel.getXmlTreeNode(xmlObj);
                    if (tn != null)
                        schemaType = tn.getSchemaType();
                }

                if (AttachmentUtils.isSwaRefType(schemaType)) {
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent) && textContent.startsWith("cid:")) {
                        textContent = textContent.substring(4);

                        try {
                            // is the textcontent already a URI?
                            new URI(textContent);
                            contentIds.put(textContent, textContent);
                        } catch (RuntimeException e) {
                            // not a URI.. try to create one..
                            String contentId = textContent + "@soapui.org";
                            cursor.setTextValue("cid:" + contentId);
                            contentIds.put(textContent, contentId);
                        }
                    }
                } else if (AttachmentUtils.isXopInclude(schemaType)) {
                    String contentId = cursor.getAttributeText(new QName("href"));
                    if (contentId != null && contentId.length() > 0) {
                        contentIds.put(contentId, contentId);
                        isXop = true;

                        Attachment[] attachments = container.getAttachmentsForPart(contentId);
                        if (attachments.length == 1) {
                            XmlCursor cur = cursor.newCursor();
                            if (cur.toParent()) {
                                String contentType = getXmlMimeContentType(cur);
                                if (contentType != null && contentType.length() > 0)
                                    attachments[0].setContentType(contentType);
                            }

                            cur.dispose();
                        }
                    }
                } else {
                    // extract contentId
                    String textContent = XmlUtils.getNodeValue(cursor.getDomNode());
                    if (StringUtils.hasContent(textContent)) {
                        Attachment attachment = null;
                        boolean isXopAttachment = false;

                        // is content a reference to a file?
                        if (container.isInlineFilesEnabled() && textContent.startsWith("file:")) {
                            String filename = textContent.substring(5);
                            if (container.isMtomEnabled()) {
                                MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                String xmimeContentType = getXmlMimeContentType(cursor);

                                if (StringUtils.isNullOrEmpty(xmimeContentType))
                                    xmimeContentType = ContentTypeHandler.getContentTypeFromFilename(filename);

                                part.setDataHandler(new DataHandler(new XOPPartDataSource(new File(filename),
                                        xmimeContentType, schemaType)));
                                part.setContentID("<" + filename + ">");
                                mp.addBodyPart(part);

                                isXopAttachment = true;
                            } else {
                                if (new File(filename).exists()) {
                                    inlineData(cursor, schemaType, new FileInputStream(filename));
                                } else {
                                    Attachment att = getAttachmentForFilename(container, filename);
                                    if (att != null)
                                        inlineData(cursor, schemaType, att.getInputStream());
                                }
                            }
                        } else {
                            Attachment[] attachmentsForPart = container.getAttachmentsForPart(textContent);
                            if (textContent.startsWith("cid:")) {
                                textContent = textContent.substring(4);
                                attachmentsForPart = container.getAttachmentsForPart(textContent);

                                Attachment[] attachments = attachmentsForPart;
                                if (attachments.length == 1) {
                                    attachment = attachments[0];
                                } else if (attachments.length > 1) {
                                    attachment = buildMulitpartAttachment(attachments);
                                }

                                isXopAttachment = container.isMtomEnabled();
                                contentIds.put(textContent, textContent);
                            }
                            // content should be binary data; is this an XOP element
                            // which should be serialized with MTOM?
                            else if (container.isMtomEnabled() && (SchemaUtils.isBinaryType(schemaType)
                                    || SchemaUtils.isAnyType(schemaType))) {
                                if ("true".equals(System.getProperty("soapui.mtom.strict"))) {
                                    if (SchemaUtils.isAnyType(schemaType)) {
                                        textContent = null;
                                    } else {
                                        for (int c = 0; c < textContent.length(); c++) {
                                            if (Character.isWhitespace(textContent.charAt(c))) {
                                                textContent = null;
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (textContent != null) {
                                    MimeBodyPart part = new PreencodedMimeBodyPart("binary");
                                    String xmimeContentType = getXmlMimeContentType(cursor);

                                    part.setDataHandler(new DataHandler(
                                            new XOPPartDataSource(textContent, xmimeContentType, schemaType)));

                                    textContent = "http://www.soapui.org/" + System.nanoTime();

                                    part.setContentID("<" + textContent + ">");
                                    mp.addBodyPart(part);

                                    isXopAttachment = true;
                                }
                            } else if (container.isInlineFilesEnabled() && attachmentsForPart != null
                                    && attachmentsForPart.length > 0) {
                                attachment = attachmentsForPart[0];
                            }
                        }

                        // add XOP include?
                        if (isXopAttachment && container.isMtomEnabled()) {
                            buildXopInclude(cursor, textContent);
                            isXop = true;
                        }
                        // inline?
                        else if (attachment != null) {
                            inlineAttachment(cursor, schemaType, attachment);
                        }
                    }
                }
            }

            cursor.toNextToken();
        }
    } finally {
        cursor.dispose();
    }

    return isXop;
}

From source file:org.eclipse.ecr.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws Exception {
    if (textType == null) {
        textType = "plain";
    }// ww w.jav  a  2s  .  c om
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}