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.xwiki.mail.internal.AttachmentMimeBodyPartFactory.java

@Override
public MimeBodyPart create(Attachment attachment, Map<String, Object> parameters) throws MessagingException {
    // Create the attachment part of the email
    MimeBodyPart attachmentPart = new MimeBodyPart();

    // Save the attachment to a temporary file on the file system and wrap it in a Java Mail Data Source.
    DataSource source = createTemporaryAttachmentDataSource(attachment);
    attachmentPart.setDataHandler(new DataHandler(source));

    attachmentPart.setHeader("Content-Type", attachment.getMimeType());

    // Add a content-id so that we can uniquely reference this attachment. This is used for example to
    // display the attachment inline in some mail HTML content.
    // Note: According to http://tools.ietf.org/html/rfc2392 the id must be enclosed in angle brackets.
    attachmentPart.setHeader("Content-ID", "<" + attachment.getFilename() + ">");

    attachmentPart.setFileName(source.getName());

    // Handle headers passed as parameter
    addHeaders(attachmentPart, parameters);

    return attachmentPart;
}

From source file:org.xwiki.mail.internal.factory.attachment.AttachmentMimeBodyPartFactory.java

@Override
public MimeBodyPart create(Attachment attachment, Map<String, Object> parameters) throws MessagingException {
    // Create the attachment part of the email
    MimeBodyPart attachmentPart = new MimeBodyPart();

    // Save the attachment to a temporary file on the file system and wrap it in a Java Mail Data Source.
    DataSource source = createTemporaryAttachmentDataSource(attachment);
    attachmentPart.setDataHandler(new DataHandler(source));

    attachmentPart.setHeader("Content-Type", attachment.getMimeType());

    // Add a content-id so that we can uniquely reference this attachment. This is used for example to
    // display the attachment inline in some mail HTML content.
    // Note: According to http://tools.ietf.org/html/rfc2392 the id must be enclosed in angle brackets.
    attachmentPart.setHeader("Content-ID", "<" + attachment.getFilename() + ">");

    attachmentPart.setFileName(attachment.getFilename());

    // Handle headers passed as parameter
    addHeaders(attachmentPart, parameters);

    return attachmentPart;
}

From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override//from   ww w .  ja v a2s.  c o  m
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public MimeBodyPart addReportAttachment() throws MessagingException {
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    String mimeType = "application/vnd.ms-excel";
    if (fileName.endsWith(".xlsx")) {
        mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    }/*www  .java 2  s  .c o  m*/
    mimeBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(reportContent, mimeType)));
    mimeBodyPart.setDisposition("attachment");
    mimeBodyPart.setFileName(fileName);

    return mimeBodyPart;
}

From source file:lucee.runtime.net.mail.HtmlEmailImpl.java

/**
 * Embeds an URL in the HTML.//  w  ww  .ja v  a  2s .  c  o m
 *
 * <p>This method allows to embed a file located by an URL into
 * the mail body.  It allows, for instance, to add inline images
 * to the email.  Inline files may be referenced with a
 * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID
 * returned by the embed function.
 *
 * <p>Example of use:<br><code><pre>
 * HtmlEmail he = new HtmlEmail();
 * he.setHtmlMsg("&lt;html&gt;&lt;img src=cid:" +
 *  embed("file:/my/image.gif","image.gif") +
 *  "&gt;&lt;/html&gt;");
 * // code to set the others email fields (not shown)
 * </pre></code>
 *
 * @param url The URL of the file.
 * @param cid A String with the Content-ID of the file.
 * @param name The name that will be set in the filename header
 * field.
 * @throws EmailException when URL supplied is invalid
 *  also see javax.mail.internet.MimeBodyPart for definitions
 *
 */
public void embed(URL url, String cid, String name) throws EmailException {
    // verify that the URL is valid
    try {
        InputStream is = url.openStream();
        is.close();
    } catch (IOException e) {
        throw new EmailException("Invalid URL");
    }

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(new URLDataSource(url)));
        mbp.setFileName(name);
        mbp.setDisposition("inline");
        mbp.addHeader("Content-ID", "<" + cid + ">");
        this.inlineImages.add(mbp);
    } catch (MessagingException me) {
        throw new EmailException(me);
    }
}

From source file:org.wf.dp.dniprorada.util.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {/*from  w  w w.java2  s. c  o  m*/
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        log.info("[_Attach:oURL]:sName=" + sName);
    } catch (Exception oException) {
        log.error("[_Attach:oURL]:sName=" + sName, oException);
    }
    return this;
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachement(final NodeRef nodeRef, MimeMultipart content, final Boolean convert)
        throws MessagingException {

    MappedByteBuffer buf;//from   w w w .jav  a 2  s.co  m
    byte[] array = new byte[0];
    ContentReader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
    String fileName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
    String type = reader.getMimetype().split("/")[0];
    if (!type.equalsIgnoreCase("image") && !reader.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_PDF)
            && convert) {
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
        String srcMimeType = reader.getMimetype();
        //String srcMimeType = ((ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT)).getMimetype();
        //String srcMimeType = this.getMimeTypeForFileName(fileName);
        ContentTransformer transformer = contentService.getTransformer(srcMimeType, MimetypeMap.MIMETYPE_PDF);
        if (transformer != null) {
            try {
                transformer.transform(reader, writer);
                reader = writer.getReader();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                fileName += ".pdf";
            } catch (ContentIOException ex) {
                logger.warn("could not transform content");
                logger.warn(ex);
                //need to refresh reader as the transformer failing closes the reader
                reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
            }
        }
    }
    try {
        buf = reader.getFileChannel().map(FileChannel.MapMode.READ_ONLY, 0, reader.getSize());
        if (reader.getSize() <= Integer.MAX_VALUE) {
            array = new byte[(int) reader.getSize()];
            buf.get(array);
        }
    } catch (IOException ex) {
        logger.error("There was an error reading file into memory.");
        logger.error(ex);
        array = new byte[0];
    }

    ByteArrayDataSource ds = new ByteArrayDataSource(array, reader.getMimetype());
    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setFileName(fileName);
    attachment.setDataHandler(new DataHandler(ds));
    content.addBodyPart(attachment);
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;/*w w  w.j ava  2s .com*/
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    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 {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            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);
        }

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

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } 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());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

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

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

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } 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:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }/*from w  ww .  j  a  va  2s .c o m*/
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}

From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java

protected void visitNode(Map cache, Node node, MimeMultipart multipart) throws Exception {

    ModelItem item = (ModelItem) node.getUserData("");
    if (item != null && item.getDeclarationView().getDatatype() != null
            && item.getDeclarationView().getDatatype().equalsIgnoreCase("anyURI")) {
        String name = item.getFilename();
        if (name == null || item.getValue() == null || item.getValue().equals("")) {
            return;
        }//from   w  w w  .  j  a  va 2s.co m

        String cid = (String) cache.get(name);
        if (cid == null) {
            int count = multipart.getCount();
            cid = name + "@part" + (count + 1);

            MimeBodyPart part = new MimeBodyPart();
            part.setContentID("<" + cid + ">");

            DataHandler dh = new DataHandler(new ModelItemDataSource(item));
            part.setDataHandler(dh);

            part.addHeader("Content-Type", item.getMediatype());
            part.addHeader("Content-Transfer-Encoding", "base64");
            part.setDisposition("attachment");
            part.setFileName(name);
            multipart.addBodyPart(part);
            cache.put(name, cid);
        }

        Element element = (Element) node;
        // remove text node
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.TEXT_NODE) {
                continue;
            }
            n.setNodeValue("cid:" + cid);
            break;
        }
    } else {
        NodeList list = node.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                visitNode(cache, n, multipart);
            }
        }
    }
}