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:servlets.mailPDF_Bronze.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  w  ww  .j a v a  2 s . co m*/
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject("LexisNexis Risk India Tracker (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName("LNIndiaTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Bronze.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {/*  www .jav a  2 s  . co  m*/
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:es.caib.sgtsic.xml.XmlManager.java

public DataHandler generateFlatXml(List<T> items) throws JAXBException {

    byte[] b = generateFlatXmlString(items).getBytes();
    String mimetype = "text/plain";
    DataSource ds = new ByteArrayDataSource(b, mimetype);
    return new DataHandler(ds);

}

From source file:servlets.mailPDF_Gold_LexisNexis.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/* ww w.  j a  v  a  2 s.  c  om*/
        System.out.println("Reached @ mailPDF_Gold_LexisNexis.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");
        String filename = request.getParameter("filename");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase64 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject(filename + " (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Gold_LexisNexis.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Gold_CitrixChina.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  w w w. j  av a  2s . com*/
        System.out.println("Reached @ mailPDF_Gold_CitrixChina.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");
        String filename = request.getParameter("filename");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase64 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject(filename + " (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Gold_CitrixChina.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:common.email.MailServiceImpl.java

/**
 * this method sends email using a given template
 * @param subject subject of a mail/* w  w  w.j  a v a 2s  . c  om*/
 * @param recipientEmail email receiver adress
 * @param mail mail text to send
 * @param from will be set
* @return true if send succeed
* @throws java.io.FileNotFoundException
 * @throws java.io.IOException
 */
protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException {
    try {
        Properties props = new Properties();
        //props.put("mailHost", mailHost);

        Session session = Session.getInstance(props);
        // construct the message
        javax.mail.Message msg = new javax.mail.internet.MimeMessage(session);
        if (from == null) {
            msg.setFrom();
        } else {
            try {
                msg.setFrom(new InternetAddress(from));
            } catch (MessagingException ex) {
                logger.error(ex);
            }
        }
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        //msg.setHeader("", user)
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8")));

        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        t.connect(mailHost, user, password);
        Address[] a = msg.getAllRecipients();
        t.sendMessage(msg, a);
        t.close();
        return true;
    } catch (MessagingException ex) {
        logger.error(ex);
        ex.printStackTrace();
        return false;
    }

}

From source file:stg.pr.engine.mailer.SmallEmailAttachment.java

/**
 * Constructs an attachment with the given name for the given input stream and content type.
 * @param name of the attachment to be associated in the email
 * @param is InputStream /*from w ww. j  a v  a2 s.com*/
 * @param contentType
 * @throws IOException
 */
public SmallEmailAttachment(String name, InputStream is, String contentType) throws IOException {
    super(name, is, contentType); //this will throw exception in case the file does not exist
    ByteArrayDataSource datasource = new ByteArrayDataSource(is, contentType);
    if (datasource.getInputStream().available() > EMailAttachment.SMALL_SIZE.longValue()) {
        throw new IllegalArgumentException(
                "Small email attachments are for file size < " + EMailAttachment.SMALL_SIZE.longValue());
    }
    this.contentType = contentType;
    this.bytes = IOUtils.toByteArray(is);
}

From source file:servlets.mailPDF.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//  w w  w  .j a  v a 2  s .  com
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");
        String filename = request.getParameter("filename");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }
        if (filename.equals("LNIndia Tracker (Gold - Weekly)")) {

            email.setFrom("reporting@groupnp.com");
            email.setSubject(filename + " (" + reportdate + ")");

            MimeMultipart part1 = new MimeMultipart();
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
            part1.addBodyPart(messageBodyPart1);
            email.addPart(part1);

            MimeMultipart part2 = new MimeMultipart();
            BodyPart messageBodyPart2 = new MimeBodyPart();
            messageBodyPart2
                    .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
            messageBodyPart2.removeHeader("Content-Transfer-Encoding");
            messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
            messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
            part2.addBodyPart(messageBodyPart2);
            email.addPart(part2);

            email.send();

        } else if (filename.equals("LNIndia Tracker (Gold - Monthly)")) {

            email.setFrom("reporting@groupnp.com");
            email.setSubject(filename + " (" + reportdate + ")");

            MimeMultipart part1 = new MimeMultipart();
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
            part1.addBodyPart(messageBodyPart1);
            email.addPart(part1);

            MimeMultipart part2 = new MimeMultipart();
            BodyPart messageBodyPart2 = new MimeBodyPart();
            messageBodyPart2
                    .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
            messageBodyPart2.removeHeader("Content-Transfer-Encoding");
            messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
            messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
            part2.addBodyPart(messageBodyPart2);
            email.addPart(part2);

            email.send();

        }

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:cz.zcu.kiv.eegdatabase.webservices.semantic.SemanticServiceImpl.java

/**
 * Generates an ontology document from POJO objects.
 * This method gives the Jena's output./*  w w w .j av a2 s  .c o  m*/
 *
 * @return
 * @throws WebServiceException
 * @throws IOException
 */
public DataHandler getOntology() throws SOAPException {
    InputStream is = null;
    byte[] bytes = null;
    ByteArrayDataSource rdf = null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        int i;
        is = simpleSemanticFactory.getOntology(null);
        while ((i = is.read()) > -1) {
            os.write(i);
        }
    } catch (IOException e) {
        log.error(e);
        throw new SOAPException(e);
    }
    rdf = new ByteArrayDataSource(os.toByteArray(), "fileBinaryStream");
    return new DataHandler(rdf);
}

From source file:org.broadleafcommerce.common.email.service.message.MessageCreator.java

public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override/*from   www  .  j a  v a  2 s. c  o m*/
        public void prepare(MimeMessage mimeMessage) throws Exception {
            EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
            EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
            boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
            message.setTo(emailUser.getEmailAddress());
            message.setFrom(info.getFromAddress());
            message.setSubject(info.getSubject());
            if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
                message.setBcc(emailUser.getBCCAddresses());
            }
            if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
                message.setCc(emailUser.getCCAddresses());
            }
            String messageBody = info.getMessageBody();
            if (messageBody == null) {
                messageBody = buildMessageBody(info, props);
            }
            message.setText(messageBody, true);
            for (Attachment attachment : info.getAttachments()) {
                ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(),
                        attachment.getMimeType());
                message.addAttachment(attachment.getFilename(), dataSource);
            }
        }
    };
    return preparator;

}