Search in sources :

Example 91 with DataSource

use of javax.activation.DataSource in project openolat by klemens.

the class MailManagerImpl method createMimeMessage.

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) {
    if (from == null || ((tos == null || tos.length == 0) && ((ccs == null || ccs.length == 0)) && (bccs == null || bccs.length == 0)))
        return null;
    try {
        MimeMessage msg = createMessage(subject, from);
        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }
        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }
        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }
        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }
            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    log.error("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        log.error("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        log.error("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        log.error("", e);
        return null;
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataHandler(javax.activation.DataHandler) Date(java.util.Date) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 92 with DataSource

use of javax.activation.DataSource in project zm-mailbox by Zimbra.

the class TextHtmlHandler method getContentImpl.

@Override
protected String getContentImpl() throws MimeHandlerException {
    if (content == null) {
        DataSource source = getDataSource();
        if (source != null) {
            InputStream is = null;
            try {
                Reader reader = getReader(is = source.getInputStream(), source.getContentType());
                content = HtmlTextExtractor.extract(reader, MimeHandlerManager.getIndexedTextLimit());
            } catch (Exception e) {
                throw new MimeHandlerException(e);
            } finally {
                ByteUtil.closeStream(is);
            }
        }
    }
    if (content == null) {
        content = "";
    }
    return content;
}
Also used : MimeHandlerException(com.zimbra.cs.mime.MimeHandlerException) InputStream(java.io.InputStream) Reader(java.io.Reader) MimeHandlerException(com.zimbra.cs.mime.MimeHandlerException) IOException(java.io.IOException) DataSource(javax.activation.DataSource)

Example 93 with DataSource

use of javax.activation.DataSource in project zm-mailbox by Zimbra.

the class TextPlainHandler method getContentImpl.

@Override
protected String getContentImpl() throws MimeHandlerException {
    if (content == null) {
        DataSource source = getDataSource();
        if (source != null) {
            String ctype = source.getContentType();
            InputStream is = null;
            try {
                Reader reader = Mime.getTextReader(is = source.getInputStream(), ctype, getDefaultCharset());
                content = ByteUtil.getContent(reader, MimeHandlerManager.getIndexedTextLimit(), false);
            } catch (IOException e) {
                throw new MimeHandlerException(e);
            } finally {
                ByteUtil.closeStream(is);
            }
        }
    }
    if (content == null) {
        content = "";
    }
    return content;
}
Also used : MimeHandlerException(com.zimbra.cs.mime.MimeHandlerException) InputStream(java.io.InputStream) Reader(java.io.Reader) IOException(java.io.IOException) DataSource(javax.activation.DataSource)

Example 94 with DataSource

use of javax.activation.DataSource in project zm-mailbox by Zimbra.

the class CreateContact method parseAttachment.

private static Attachment parseAttachment(Element elt, String name, ZimbraSoapContext zsc, OperationContext octxt, Contact existing) throws ServiceException {
    // check for uploaded attachment
    String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    if (attachId != null) {
        if (Contact.isSMIMECertField(name)) {
            elt.setText(parseCertificate(elt, name, zsc, octxt, existing));
            return null;
        } else {
            Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId, zsc.getAuthToken());
            UploadDataSource uds = new UploadDataSource(up);
            return new Attachment(new DataHandler(uds), name, (int) up.getSize());
        }
    }
    int itemId = (int) elt.getAttributeLong(MailConstants.A_ID, -1);
    String part = elt.getAttribute(MailConstants.A_PART, null);
    if (itemId != -1 || (part != null && existing != null)) {
        MailItem item = itemId == -1 ? existing : getRequestedMailbox(zsc).getItemById(octxt, itemId, MailItem.Type.UNKNOWN);
        try {
            if (item instanceof Contact) {
                Contact contact = (Contact) item;
                if (part != null && !part.equals("")) {
                    try {
                        int partNum = Integer.parseInt(part) - 1;
                        if (partNum >= 0 && partNum < contact.getAttachments().size()) {
                            Attachment att = contact.getAttachments().get(partNum);
                            return new Attachment(att.getDataHandler(), name, att.getSize());
                        }
                    } catch (NumberFormatException nfe) {
                    }
                    throw ServiceException.INVALID_REQUEST("invalid contact part number: " + part, null);
                } else {
                    VCard vcf = VCard.formatContact(contact);
                    return new Attachment(vcf.getFormatted().getBytes("utf-8"), "text/x-vcard; charset=utf-8", name, vcf.fn + ".vcf");
                }
            } else if (item instanceof Message) {
                Message msg = (Message) item;
                if (part != null && !part.equals("")) {
                    try {
                        MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
                        if (mp == null) {
                            throw MailServiceException.NO_SUCH_PART(part);
                        }
                        DataSource ds = new MimePartDataSource(mp);
                        return new Attachment(new DataHandler(ds), name);
                    } catch (MessagingException me) {
                        throw ServiceException.FAILURE("error parsing blob", me);
                    }
                } else {
                    DataSource ds = new MessageDataSource(msg);
                    return new Attachment(new DataHandler(ds), name, (int) msg.getSize());
                }
            } else if (item instanceof Document) {
                Document doc = (Document) item;
                if (part != null && !part.equals("")) {
                    throw MailServiceException.NO_SUCH_PART(part);
                }
                DataSource ds = new DocumentDataSource(doc);
                return new Attachment(new DataHandler(ds), name, (int) doc.getSize());
            }
        } catch (IOException ioe) {
            throw ServiceException.FAILURE("error attaching existing item data", ioe);
        } catch (MessagingException e) {
            throw ServiceException.FAILURE("error attaching existing item data", e);
        }
    }
    return null;
}
Also used : Message(com.zimbra.cs.mailbox.Message) MessagingException(javax.mail.MessagingException) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) Document(com.zimbra.cs.mailbox.Document) Contact(com.zimbra.cs.mailbox.Contact) ParsedContact(com.zimbra.cs.mime.ParsedContact) MimePartDataSource(javax.mail.internet.MimePartDataSource) UploadDataSource(com.zimbra.cs.service.UploadDataSource) MessageDataSource(com.zimbra.cs.mailbox.MessageDataSource) DocumentDataSource(com.zimbra.cs.mailbox.DocumentDataSource) DataSource(javax.activation.DataSource) MailItem(com.zimbra.cs.mailbox.MailItem) MessageDataSource(com.zimbra.cs.mailbox.MessageDataSource) MimePartDataSource(javax.mail.internet.MimePartDataSource) DocumentDataSource(com.zimbra.cs.mailbox.DocumentDataSource) MimePart(javax.mail.internet.MimePart) UploadDataSource(com.zimbra.cs.service.UploadDataSource) VCard(com.zimbra.cs.service.formatter.VCard)

Example 95 with DataSource

use of javax.activation.DataSource in project spring-framework by spring-projects.

the class MimeMessageHelper method addAttachment.

/**
	 * Add an attachment to the MimeMessage, taking the content from an
	 * {@code org.springframework.core.io.InputStreamResource}.
	 * <p>Note that the InputStream returned by the InputStreamSource
	 * implementation needs to be a <i>fresh one on each call</i>, as
	 * JavaMail will invoke {@code getInputStream()} multiple times.
	 * @param attachmentFilename the name of the attachment as it will
	 * appear in the mail
	 * @param inputStreamSource the resource to take the content from
	 * (all of Spring's Resource implementations can be passed in here)
	 * @param contentType the content type to use for the element
	 * @throws MessagingException in case of errors
	 * @see #addAttachment(String, java.io.File)
	 * @see #addAttachment(String, javax.activation.DataSource)
	 * @see org.springframework.core.io.Resource
	 */
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
    Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
    if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
        throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " + "JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
    }
    DataSource dataSource = createDataSource(inputStreamSource, contentType, attachmentFilename);
    addAttachment(attachmentFilename, dataSource);
}
Also used : Resource(org.springframework.core.io.Resource) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Aggregations

DataSource (javax.activation.DataSource)196 DataHandler (javax.activation.DataHandler)114 FileDataSource (javax.activation.FileDataSource)60 MimeBodyPart (javax.mail.internet.MimeBodyPart)53 MimeMultipart (javax.mail.internet.MimeMultipart)48 MimeMessage (javax.mail.internet.MimeMessage)39 InputStream (java.io.InputStream)37 IOException (java.io.IOException)36 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)35 ByteArrayInputStream (java.io.ByteArrayInputStream)33 File (java.io.File)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)30 Test (org.junit.Test)30 InternetAddress (javax.mail.internet.InternetAddress)27 Properties (java.util.Properties)26 MessagingException (javax.mail.MessagingException)25 Multipart (javax.mail.Multipart)24 Session (javax.mail.Session)21 BodyPart (javax.mail.BodyPart)19 ArrayList (java.util.ArrayList)16