Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:org.apromore.service.impl.CanoniserServiceImplIntgTest.java

@Test
public void deCanoniseWithoutAnnotationsSuccessXPDL() throws Exception {
    String name = "XPDL 2.2";
    InputStream cpf = new ByteArrayDataSource(CanonicalNoAnnotationModel.CANONICAL_XML, "text/xml")
            .getInputStream();//  w w w .  ja v a  2 s  .  co  m

    DecanonisedProcess dp = cSrv.deCanonise(name, getTypeFromXML(cpf), null, emptyCanoniserRequest);

    MatcherAssert.assertThat(dp.getNativeFormat(), Matchers.notNullValue());
    MatcherAssert.assertThat(dp.getMessages(), Matchers.notNullValue());
}

From source file:mitm.djigzo.web.pages.admin.backup.BackupManager.java

private Object restore() {
    Check.notNull(file, "file");

    Object result = null;//from w  ww  . j  ava2 s .  co  m

    restoreFailure = false;

    try {
        DataSource source = new ByteArrayDataSource(file.getStream(), file.getContentType());
        DataHandler dataHandler = new DataHandler(source);

        BinaryDTO backup = new BinaryDTO(dataHandler);

        backupWS.restore(backup, password);

        result = Restarting.class;
    } catch (IOException e) {
        restoreFailure(e);
    } catch (WebServiceCheckedException e) {
        restoreFailure(e);
    }

    return result;
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal)
        throws MessagingException {
    if (appockMail.getBonLivraison() == null) {
        msg.setContent(contenuFinal, "text/html; charset=utf-8");
    } else {//from  w w  w .  ja v  a 2 s.c  om
        BonLivraison bonLivraison = appockMail.getBonLivraison();
        Multipart multipart = new MimeMultipart();
        BodyPart attachmentBodyPart = new MimeBodyPart();

        File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison());

        ByteArrayDataSource bds = null;
        try {
            bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()),
                    bonLivraison.getMimeType().getLibelle());
        } catch (IOException e) {
            e.printStackTrace();
        }

        attachmentBodyPart.setDataHandler(new DataHandler(bds));
        attachmentBodyPart.setFileName(bonLivraison.getNomFichier());
        multipart.addBodyPart(attachmentBodyPart);

        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8");
        multipart.addBodyPart(htmlBodyPart);
        msg.setContent(multipart);
    }
}

From source file:org.sakaiproject.feedback.util.SakaiProxy.java

public void sendEmail(String fromUserId, String senderAddress, String toAddress,
        boolean addNoContactEmailMessage, String siteId, String feedbackType, String userTitle,
        String userContent, List<FileItem> fileItems, boolean siteExists, String browserNameAndVersion,
        String osNameAndVersion, String browserSize, String screenSize, String plugins, String ip,
        String currentTime) {//from   www  .jav a2 s. c o m

    final List<Attachment> attachments = new ArrayList<Attachment>();

    if (fileItems.size() > 0) {
        for (FileItem fileItem : fileItems) {
            String name = fileItem.getName();

            if (name.contains("/")) {
                name = name.substring(name.lastIndexOf("/") + 1);
            } else if (name.contains("\\")) {
                name = name.substring(name.lastIndexOf("\\") + 1);
            }

            attachments.add(
                    new Attachment(new ByteArrayDataSource(fileItem.get(), fileItem.getContentType()), name));
        }
    }

    String fromAddress = senderAddress;
    String fromName = "User not logged in";
    String userId = "";
    String userEid = "";

    if (fromUserId != null) {
        User user = getUser(fromUserId);
        fromAddress = user.getEmail();
        fromName = user.getDisplayName();
        userId = user.getId();
        userEid = user.getEid();
    }

    if (fromAddress == null) {
        logger.error("No email for reporter: " + fromUserId + ". No email will be sent.");
        return;
    }

    final String siteLocale = getSiteProperty(siteId, "locale_string");

    Locale locale = null;

    if (siteLocale != null) {

        String[] localeParts = siteLocale.split("_");

        if (localeParts.length == 1) {
            locale = new Locale(localeParts[0]);
        } else if (localeParts.length == 2) {
            locale = new Locale(localeParts[0], localeParts[1]);
        } else {
            locale = Locale.getDefault();
        }
    } else {
        locale = Locale.getDefault();
    }

    final ResourceLoader rb = new ResourceLoader("org.sakaiproject.feedback");

    String subjectTemplate = null;

    if (feedbackType.equals(Constants.CONTENT)) {
        subjectTemplate = rb.getString("content_email_subject_template");
    } else if (feedbackType.equals(Constants.HELPDESK)) {
        subjectTemplate = rb.getString("help_email_subject_template");
    } else {
        subjectTemplate = rb.getString("technical_email_subject_template");
    }

    final String formattedSubject = MessageFormat.format(subjectTemplate, new String[] { fromName });

    final Site site = getSite(siteId);

    final String siteTitle = siteExists ? site.getTitle() : "N/A (Site does not exist)";

    final String workerNode = serverConfigurationService.getServerId();
    final String siteUrl = serverConfigurationService.getPortalUrl() + "/site/"
            + (siteExists ? site.getId() : siteId);

    String noContactEmailMessage = "";

    final String instance = serverConfigurationService.getServerIdInstance();

    final String bodyTemplate = rb.getString("email_body_template");
    String formattedBody = MessageFormat.format(bodyTemplate,
            new String[] { noContactEmailMessage, userId, userEid, fromName, fromAddress, siteTitle, siteId,
                    siteUrl, instance, userTitle, userContent, "\n", browserNameAndVersion, osNameAndVersion,
                    browserSize, screenSize, plugins, ip, workerNode, currentTime });

    if (feedbackType.equals(Constants.CONTENT)) {
        formattedBody = formattedBody + "\n\n\n" + rb.getString("email_body_template_note");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("fromName: " + fromName);
        logger.debug("fromAddress: " + fromAddress);
        logger.debug("toAddress: " + toAddress);
        logger.debug("userContent: " + userContent);
        logger.debug("userTitle: " + userTitle);
        logger.debug("subjectTemplate: " + subjectTemplate);
        logger.debug("bodyTemplate: " + bodyTemplate);
        logger.debug("formattedSubject: " + formattedSubject);
        logger.debug("formattedBody: " + formattedBody);
    }

    final EmailMessage msg = new EmailMessage();

    msg.setFrom(new EmailAddress(fromAddress, fromName));
    msg.setContentType(ContentType.TEXT_PLAIN);

    msg.setSubject(formattedSubject);
    msg.setBody(formattedBody);

    if (attachments != null) {
        for (Attachment attachment : attachments) {
            msg.addAttachment(attachment);
        }
    }

    // Copy the sender in
    msg.addRecipient(RecipientType.CC, fromName, fromAddress);

    msg.addRecipient(RecipientType.TO, toAddress);

    new Thread(new Runnable() {
        public void run() {
            try {
                emailService.send(msg, true);
            } catch (Exception e) {
                logger.error("Failed to send email.", e);
            }
        }
    }, "Feedback Email Thread").start();
}

From source file:eu.ggnet.dwoss.redtape.DocumentSupporterOperation.java

/**
 * This method send document to the e-Mail address that is in the customer set.
 * <p/>/*from   www  .  ja v  a  2  s.c o  m*/
 * @param document This is the Document that will be send.
 * @throws UserInfoException if the sending of the Mail is not successful.
 * @throws RuntimeException  if problems exist in the JasperExporter
 */
@Override
public void mail(Document document, DocumentViewType jtype) throws UserInfoException, RuntimeException {
    UiCustomer customer = customerService.asUiCustomer(document.getDossier().getCustomerId());

    String customerMailAddress = customerService.asCustomerMetaData(document.getDossier().getCustomerId())
            .getEmail();
    if (customerMailAddress == null) {
        throw new UserInfoException(
                "Kunde hat keine E-Mail Hinterlegt! Senden einer E-Mail ist nicht Mglich!");
    }

    String doctype = (jtype == DocumentViewType.DEFAULT ? document.getType().getName() : jtype.getName());

    try (InputStream is = mandator.getMailTemplateLocation().toURL().openStream();
            InputStreamReader templateReader = new InputStreamReader(is)) {
        String text = new MailDocumentParameter(customer.toTitleNameLine(), doctype)
                .eval(IOUtils.toString(templateReader));
        MultiPartEmail email = mandator.prepareDirectMail();

        email.setCharset("UTF-8");

        email.addTo(customerMailAddress);
        email.setSubject(document.getType().getName() + " | " + document.getDossier().getIdentifier());
        email.setMsg(text + mandator.getDefaultMailSignature());
        email.attach(new ByteArrayDataSource(JasperExportManager.exportReportToPdf(jasper(document, jtype)),
                "application/pdf"), "Dokument.pdf", "Das ist das Dokument zu Ihrem Aufrag als PDF.");
        for (MandatorMailAttachment mma : mandator.getDefaultMailAttachment()) {
            email.attach(mma.getAttachmentData().toURL(), mma.getAttachmentName(),
                    mma.getAttachmentDescription());
        }
        email.send();
    } catch (EmailException ex) {
        L.error("Error on Mail sending", ex);
        throw new UserInfoException("Das senden der Mail war nicht erfolgreich!\n" + ex.getMessage());
    } catch (IOException | JRException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.domibus.ebms3.sender.EbMS3MessageBuilder.java

private void attachPayload(PartInfo partInfo, SOAPMessage message)
        throws ParserConfigurationException, SOAPException, IOException, SAXException {
    String mimeType = null;//ww  w.  ja  v  a  2 s.c om
    boolean compressed = false;
    for (Property prop : partInfo.getPartProperties().getProperties()) {
        if (Property.MIME_TYPE.equals(prop.getName())) {
            mimeType = prop.getValue();
        }
        if (CompressionService.COMPRESSION_PROPERTY_KEY.equals(prop.getName())
                && CompressionService.COMPRESSION_PROPERTY_VALUE.equals(prop.getValue())) {
            compressed = true;
        }
    }
    byte[] binaryData = this.attachmentDAO.loadBinaryData(partInfo.getEntityId());
    DataSource dataSource = new ByteArrayDataSource(binaryData,
            compressed ? CompressionService.COMPRESSION_PROPERTY_VALUE : mimeType);
    DataHandler dataHandler = new DataHandler(dataSource);
    if (partInfo.isInBody() && mimeType != null && mimeType.toLowerCase().contains("xml")) { //TODO: respect empty soap body config
        this.documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = this.documentBuilderFactory.newDocumentBuilder();
        message.getSOAPBody().addDocument(builder.parse(dataSource.getInputStream()));
        partInfo.setHref(null);
        return;
    }
    AttachmentPart attachmentPart = message.createAttachmentPart(dataHandler);
    attachmentPart.setContentId(partInfo.getHref());
    message.addAttachmentPart(attachmentPart);
}

From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java

private void sendHTML(final String message) throws MessagingException, IOException {
    if (message == null || message.isEmpty()) {
        throw new IllegalArgumentException("message");
    }/* www . j a  v a 2 s . c o m*/

    final String host = properties.getConfigString("host");

    final Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);

    final String port = properties.getConfigString("port", null);
    if (port != null) {
        props.setProperty("mail.smtp.port", port);
    }

    if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) {
        props.setProperty("mail.smtp.ssl.enable", "true");
    }

    final Session session = Session.getInstance(props, null);
    //        session.setDebug( true );

    final javax.mail.Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(properties.getConfigString("from")));

    msg.setRecipients(javax.mail.Message.RecipientType.TO,
            InternetAddress.parse(properties.getConfigString("to"), false));

    msg.setSubject("superpipes error message");

    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html")));

    msg.setHeader("X-Mailer", "superpipes");

    Transport t = null;
    try {
        t = session.getTransport("smtp");

        final String username = properties.getConfigString("username", null);
        final String password = properties.getConfigString("password", null);
        if (username == null || password == null) {
            t.connect();
        } else {
            if (port == null || port.isEmpty()) {
                t.connect(host, username, password);
            } else {
                t.connect(host, Integer.parseInt(port), username, password);
            }
        }

        t.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }
}

From source file:org.apromore.service.impl.CanoniserServiceImplIntgTest.java

@Test
public void deCanoniseWithAnnotationsSuccessXPDL() throws Exception {
    String name = "XPDL 2.2";
    InputStream cpf = new ByteArrayDataSource(CanonicalWithAnnotationModel.CANONICAL_XML, "text/xml")
            .getInputStream();/*  w  w  w .ja  va  2  s  . c o m*/
    DataSource anf = new ByteArrayDataSource(CanonicalWithAnnotationModel.ANNOTATION_XML, "text/xml");

    DecanonisedProcess dp = cSrv.deCanonise(name, getTypeFromXML(cpf), getANFTypeFromXML(anf),
            emptyCanoniserRequest);

    MatcherAssert.assertThat(dp.getNativeFormat(), Matchers.notNullValue());
    MatcherAssert.assertThat(dp.getMessages(), Matchers.notNullValue());
}

From source file:org.mayocat.shop.billing.internal.SendEmailsWhenOrderIsPaid.java

/**
 * Sends the actual notification mails./*  w w  w. j a  v a  2s .  c  o  m*/
 *
 * Warning: Since this is done in a spawned thread, so we can't use the web context thread local data from there
 *
 * @param order the order concerned by the notifications mails
 * @param tenant the tenant concerned by the notifications mails
 * @param customerLocale the locale the customer browsed the site in when checking out
 * @param tenantLocale the main locale of the tenant
 * @param withInvoice whether to generate and include a PDF invoice with the notification mail
 */
private void sendNotificationMails(Order order, Tenant tenant, Locale customerLocale, Locale tenantLocale,
        boolean withInvoice) {
    try {
        Customer customer = order.getCustomer();

        Optional<Address> billingAddress;
        if (order.getBillingAddress() != null) {
            billingAddress = Optional.of(order.getBillingAddress());
        } else {
            billingAddress = Optional.absent();
        }
        Optional<Address> deliveryAddress;
        if (order.getDeliveryAddress() != null) {
            deliveryAddress = Optional.of(order.getDeliveryAddress());
        } else {
            deliveryAddress = Optional.absent();
        }

        Map<String, Object> emailContext = prepareMailContext(order, customer, billingAddress, deliveryAddress,
                tenant, tenantLocale);

        String customerEmail = customer.getEmail();

        MailTemplate customerNotificationEmail = getCustomerNotificationEmail(tenant, customerEmail,
                customerLocale);
        MailTemplate tenantNotificationEmail = getTenantNotificationEmail(tenant, tenantLocale);

        // Generate invoice number and add add invoice to email if invoicing is enabled
        if (withInvoice) {
            try {
                // TODO: there should be a way to not load the whole PDF in memory...
                ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
                InvoiceNumber invoiceNumber = invoicingService.getOrCreateInvoiceNumber(order);
                invoicingService.generatePdfInvoice(order, pdfStream);

                MailAttachment attachment = new MailAttachment(
                        new ByteArrayDataSource(pdfStream.toByteArray(), "application/pdf"),
                        "invoice-" + invoiceNumber.getNumber() + ".pdf");

                customerNotificationEmail.addAttachment(attachment);
                tenantNotificationEmail.addAttachment(attachment);
            } catch (InvoicingException e) {
                logger.error("Failed to to generate invoice for email", e);
            }
        }

        sendNotificationMail(customerNotificationEmail, emailContext, tenant);
        sendNotificationMail(tenantNotificationEmail, emailContext, tenant);
    } catch (Exception e) {
        logger.error("Failed to send order notification email when sending email", e);
    }
}

From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java

@Override
public void sendNotification(String smtpSender, String replyTo, String recipient, String subject,
        String htmlContent, String inReplyTo, String references) throws SendFailedException {

    if (smtpServer.equals("")) {
        logger.warn("Mail notifications are disabled.");
        return;//from www.j  av  a2 s.c  om
    }
    // get the mail session
    Session session = getMailSession();

    // Define message
    MimeMessage messageMim = new MimeMessage(session);

    try {
        messageMim.setFrom(new InternetAddress(smtpSender));

        if (replyTo != null) {
            InternetAddress reply[] = new InternetAddress[1];
            reply[0] = new InternetAddress(replyTo);
            messageMim.setReplyTo(reply);
        }

        messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));

        if (inReplyTo != null && inReplyTo != "") {
            // This field should contain only ASCCI character (RFC 822)
            if (isPureAscii(inReplyTo)) {
                messageMim.setHeader("In-Reply-To", inReplyTo);
            }
        }

        if (references != null && references != "") {
            // This field should contain only ASCCI character (RFC 822)  
            if (isPureAscii(references)) {
                messageMim.setHeader("References", references);
            }
        }

        messageMim.setSubject(subject, charset);

        // Create a "related" Multipart message
        // content type is multipart/alternative
        // it will contain two part BodyPart 1 and 2
        Multipart mp = new MimeMultipart("alternative");

        // BodyPart 2
        // content type is multipart/related
        // A multipart/related is used to indicate that message parts should
        // not be considered individually but rather
        // as parts of an aggregate whole. The message consists of a root
        // part (by default, the first) which reference other parts inline,
        // which may in turn reference other parts.
        Multipart html_mp = new MimeMultipart("related");

        // Include an HTML message with images.
        // BodyParts: the HTML file and an image

        // Get the HTML file
        BodyPart rel_bph = new MimeBodyPart();
        rel_bph.setDataHandler(
                new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset)));
        html_mp.addBodyPart(rel_bph);

        // Create the second BodyPart of the multipart/alternative,
        // set its content to the html multipart, and add the
        // second bodypart to the main multipart.
        BodyPart alt_bp2 = new MimeBodyPart();
        alt_bp2.setContent(html_mp);
        mp.addBodyPart(alt_bp2);

        messageMim.setContent(mp);

        // RFC 822 "Date" header field
        // Indicates that the message is complete and ready for delivery
        messageMim.setSentDate(new GregorianCalendar().getTime());

        // Since we used html tags, the content must be marker as text/html
        // messageMim.setContent(content,"text/html; charset="+charset);

        Transport tr = session.getTransport("smtp");

        // Connect to smtp server, if needed
        if (needsAuth) {
            tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword);
            messageMim.saveChanges();
            tr.sendMessage(messageMim, messageMim.getAllRecipients());
            tr.close();
        } else {
            // Send message
            Transport.send(messageMim);
        }
    } catch (SendFailedException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient,
                e);
        throw e;
    } catch (MessagingException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    } catch (Exception e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    }
}