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:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;//from  w w  w  .  j a  va  2  s  .co  m
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}

From source file:com.dominion.salud.pedicom.negocio.tools.MAILService.java

/**
 * configura el ciente de correo y envia el correo con un adjunto
 *
 * @param to/*from ww  w.  j a  v  a2 s .c om*/
 * @param attach el archivo que se adjunta en el correo
 * @param centro nombre del centro desde el que se envia
 * @throws Exception
 */
public void sendByMail(String to, Object attach, String centro) throws Exception {
    logger.debug("          Iniciando la configuracion del mail con sus parametros correspondientes ,"
            + " obtenemos los parametros de environment");

    String dataBase = routingDataSource.dbActual();
    allDataSources.getDatasources();

    Datasources dat = null;
    for (Datasources datas : allDataSources.getDatasources()) {
        if (datas.getNombreDatasource().equals(dataBase)) {
            dat = datas;
            break;
        }
    }
    if (StringUtils.isBlank(StringUtils.trim(dat.getHost()))) {
        throw new Exception(
                "El host es [" + StringUtils.trim(dat.getHost()) + "] , error de host desconocido o erroneo");
    }
    logger.debug("          El host es [" + StringUtils.trim(dat.getHost()) + "]");

    if (StringUtils.isBlank(StringUtils.trim(dat.getUsernameEmail()))) {
        throw new Exception("El usuario es [" + StringUtils.trim(dat.getUsernameEmail())
                + "], error de login en el correo , usuario desconocido o erroneo");
    }
    logger.debug("          El usuario es [" + StringUtils.trim(dat.getUsernameEmail()) + "]");

    if (StringUtils.isBlank(StringUtils.trim(dat.getPasswordEmail()))) {
        throw new Exception("La contrasea es [" + StringUtils.trim(dat.getPasswordEmail())
                + "], error de login en el correo , contrasea desconocida o erronea");
    }
    logger.debug("          La contrasea es [" + StringUtils.trim(dat.getPasswordEmail()) + "]");

    if (StringUtils.isBlank(to)) {
        throw new Exception("El destinatario es [" + to + "], no se especificaron destinatarios.");
    }
    logger.debug("          El destinatario es [" + to + "]");

    /*if (dat.getPort()== null) {
    throw new Exception("El puerto es [" + StringUtils.trim(environment.getProperty("mail.port")) + "], el puerto del servidor de correo falla");
    }*/
    logger.debug("          El puerto es [" + dat.getPort() + "]");

    /*if (StringUtils.isBlank(StringUtils.trim(environment.getProperty("mail.TLS")))) {
    throw new Exception("El TLS es [" + StringUtils.trim(environment.getProperty("mail.TLS")) + "]");
    }*/
    logger.debug("          El TLS es [" + dat.getTLS() + "]");

    System.setProperty("mail.imap.auth.plain.disable", "true");

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(StringUtils.trim(dat.getHost()));
    email.setAuthenticator(new DefaultAuthenticator(StringUtils.trim(dat.getUsernameEmail()),
            StringUtils.trim(dat.getPasswordEmail())));
    email.setFrom(StringUtils.trim(StringUtils.trim(dat.getUsernameEmail())), centro);
    email.setDebug(true);
    email.setSmtpPort(dat.getPort());
    email.setStartTLSEnabled(dat.getTLS());
    email.setSSLOnConnect(dat.getSSL());
    DataSource source = null;
    if (attach != null) {
        logger.debug("          Adjuntando pdf");
        source = new ByteArrayDataSource((InputStream) attach, "application/pdf");
        email.attach(source, "Pedido de centro " + centro + ".pdf", "Pedido de centro " + centro);
    }
    email.setSubject("Pedido de centro [" + centro + "]");
    logger.debug("          Realizando envio");
    email.addTo(to);
    email.send();

    try {
        if (!StringUtils.isBlank(StringUtils.trim(dat.getMailCC()))) {
            logger.debug("          Enviando a CC: " + dat.getMailCC());
            MultiPartEmail emailCC = new MultiPartEmail();
            emailCC.setHostName(StringUtils.trim(dat.getHost()));
            emailCC.setAuthenticator(new DefaultAuthenticator(StringUtils.trim(dat.getUsernameEmail()),
                    StringUtils.trim(dat.getPasswordEmail())));
            emailCC.setFrom(StringUtils.trim(StringUtils.trim(dat.getUsernameEmail())), centro);
            emailCC.setDebug(true);
            emailCC.setSmtpPort(dat.getPort());
            emailCC.setStartTLSEnabled(dat.getTLS());
            emailCC.setSSLOnConnect(dat.getSSL());
            if (attach != null) {
                logger.debug("          Adjuntando pdf a copia");
                emailCC.attach(source, "Pedido de centro " + centro + ".pdf", "Pedido de centro " + centro);
            }
            emailCC.setSubject("Pedido de centro " + centro);
            emailCC.addCc(StringUtils.split(StringUtils.trim(dat.getMailCC()), ","));
            emailCC.send();
        }
    } catch (Exception e) {
        logger.warn("          Se han producido errores al enviar los CC: " + e.toString());
    }
    logger.debug("     Finalizando envio email");

}

From source file:org.mule.transport.email.transformers.ObjectToMimeMessage.java

protected BodyPart getPayloadBodyPart(Object payload, String contentType)
        throws MessagingException, TransformerException, IOException {
    DataHandler handler;/*from  www  . j  av  a2 s.  c om*/
    if (payload instanceof String) {
        handler = new DataHandler(new ByteArrayDataSource((String) payload, contentType));
    } else if (payload instanceof byte[]) {
        handler = new DataHandler(new ByteArrayDataSource((byte[]) payload, contentType));
    } else if (payload instanceof Serializable) {
        handler = new DataHandler(new ByteArrayDataSource(
                (byte[]) new SerializableToByteArray().transform(payload), contentType));
    } else {
        throw new IllegalArgumentException();
    }
    BodyPart part = new MimeBodyPart();
    part.setDataHandler(handler);
    part.setDescription("Payload");
    return part;
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;/* w  w  w.  j  ava2s  .com*/

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

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

}

From source file:org.jasig.portlet.blackboardvcportlet.dao.ws.impl.PresentationWSDaoImplTestBase.java

private BlackboardPresentationResponse createRepoPresentation() throws Exception {
    InputStream is = new ByteArrayInputStream("fdsdfsfsdadsfasfda".getBytes());
    ByteArrayDataSource rawData = new ByteArrayDataSource(is, "video/mpeg");
    DataHandler dataHandler = new DataHandler(rawData);

    BlackboardPresentationResponse presenetation = dao.uploadPresentation(user.getUniqueId(), "test.elp",
            "aliens", dataHandler);
    presentations.put(presenetation.getPresentationId(), presenetation);
    return presenetation;
}

From source file:mitm.application.djigzo.ws.impl.BackupWSImpl.java

@Override
@StartTransaction/*from  w  w  w. jav  a 2 s .c  o m*/
public BinaryDTO backupDirect(String password) throws WebServiceCheckedException {
    try {
        /*
         * The backup will be store in memory. If we store the backup in a file we need to create a 
         * temp file to support concurrent access. The problem with this is that we can only delete
         * the file when it has been received by the end party but then we already lost control.
         * Storing the backup in memory can take some memory so we will add a max backup size.
         * If we need to support much larger backup sizes we can always resort to a file cache
         * which will periodically delete stale files.
         */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStream output = new SizeLimitedOutputStream(bos, maxBackupSize, true);

        BackupDriver backupDriver = new OutputStreamBackupDriver(output);

        String identifier = backupMaker.backup(backupDriver, password);

        DataSource source = new ByteArrayDataSource(bos.toByteArray(), "application/octet-stream");
        DataHandler dataHandler = new DataHandler(source);

        return new BinaryDTO(dataHandler, identifier);
    } catch (BackupException e) {
        logger.error("restore failed.", e);

        throw new WebServiceCheckedException(ExceptionUtils.getRootCauseMessage(e));
    } catch (RuntimeException e) {
        logger.error("restore failed.", e);

        throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
    }
}

From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java

@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) {
        // Get the email properties entered via Share Form
        String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME);
        String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME);
        String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME);

        // Get document filename
        Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef,
                ContentModel.PROP_NAME);
        if (filename == null) {
            throw new AlfrescoRuntimeException("Document filename is null");
        }/*ww w .j  a  va2 s  .  c om*/
        String documentName = (String) filename;

        try {
            // Create mail session
            Properties mailServerProperties = new Properties();
            mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.host", "localhost");
            mailServerProperties.put("mail.smtp.port", "2525");
            Session session = Session.getDefaultInstance(mailServerProperties, null);
            session.setDebug(false);

            // Define message
            Message message = new MimeMessage(session);
            String fromAddress = "training@alfresco.com";
            message.setFrom(new InternetAddress(fromAddress));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // Create the message part with body text
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create the Attachment part
            //
            //  Get the document content bytes
            byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName);
            if (documentData == null) {
                throw new AlfrescoRuntimeException("Document content is null");
            }
            //  Attach document
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData,
                    new MimetypesFileTypeMap().getContentType(documentName))));
            messageBodyPart.setFileName(documentName);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send mail
            Transport.send(message);

            // Set status on node as "sent via email"
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
            properties.put(ContentModel.PROP_ORIGINATOR, fromAddress);
            properties.put(ContentModel.PROP_ADDRESSEE, to);
            properties.put(ContentModel.PROP_SUBJECT, subject);
            properties.put(ContentModel.PROP_SENTDATE, new Date());
            serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED,
                    properties);
        } catch (MessagingException me) {
            me.printStackTrace();
            throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage());
        }
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.DataSourceBlockImpl.java

@Override
protected Object _getBOFromOM(OMElement omElement, Object busContext)
        throws XMLStreamException, WebServiceException {
    Object busObject;//  w  ww.jav  a2 s  . c  om

    // Shortcut to get business object from existing data source
    if (omElement instanceof OMSourcedElement) {
        OMDataSource ds = ((OMSourcedElement) omElement).getDataSource();
        if (ds instanceof SourceDataSource) {
            return ((SourceDataSource) ds).getObject();
        }
    }

    // If the message is a fault, there are some special gymnastics that we have to do
    // to get this working for all of the handler scenarios.  
    boolean hasFault = false;
    if ((parent != null && parent.isFault())
            || omElement.getQName().getLocalPart().equals(SOAP11Constants.SOAPFAULT_LOCAL_NAME)) {
        hasFault = true;
    }

    // Transform reader into business object
    if (!hasFault) {
        busObject = ((OMSourcedElement) omElement).getDataSource();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        omElement.serialize(baos);
        busObject = new ByteArrayDataSource(baos.toByteArray(), "UTF-8");
    }
    return busObject;
}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Returns a data-handler for this part//from  w  w  w.  j  a v  a2  s.c o m
 * @return a data-handler for this part
 */
public DataHandler getDataHandler(Cache<URL, CachedUrlData> cache) throws MessagingException {
    if (file != null) {
        return new DataHandler(new FileDataSource(file));
    } else if (url != null) {
        return new DataHandler(new CachedUrlDataSource(url, cache));
    } else {
        return new DataHandler(new ByteArrayDataSource(content, contentType));
    }
}

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

@Test(expected = JAXBException.class)
public void deCanoniseWithoutAnnotationsFailure() throws Exception {
    String name = "Canonical";
    InputStream cpf = new ByteArrayDataSource("<XML/>", "text/xml").getInputStream();
    cSrv.deCanonise(name, getTypeFromXML(cpf), null, emptyCanoniserRequest);
}