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:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {// ww w .  j  a  va  2s .  c  o  m
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);/*  w  w w  . ja v a2s  .  c o  m*/
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:com.adaptris.core.MimeEncoderImpl.java

protected MimeBodyPart asMimePart(Exception e) throws Exception {
    MimeBodyPart p = new MimeBodyPart();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream();
            PrintStream printer = new PrintStream(out, true)) {
        e.printStackTrace(printer);/*from  www . j a  va  2 s .  com*/
        p.setDataHandler(new DataHandler(new ByteArrayDataSource(out.toByteArray())));
    }
    return p;
}

From source file:com.googlecode.ddom.mime.JavaMailTest.java

private void test(boolean preamble) throws Exception {
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart bodyPart1 = new MimeBodyPart();
    StringBuilder buffer = new StringBuilder();
    for (int i = 0; i < 1000; i++) {
        buffer.append('(');
        buffer.append(i);/*from www  .j  a  va2s . c  o  m*/
        buffer.append(')');
    }
    String content1 = buffer.toString();
    bodyPart1
            .setDataHandler(new DataHandler(new ByteArrayDataSource(content1.getBytes("UTF-8"), "text/plain")));
    Map<String, String> headers1 = new HashMap<String, String>();
    headers1.put("Content-ID", "<1@example.com>");
    headers1.put("Content-Type", "text/plain; charset=UTF-8");
    setHeaders(bodyPart1, headers1);
    multipart.addBodyPart(bodyPart1);

    MimeBodyPart bodyPart2 = new MimeBodyPart();
    byte[] content2 = new byte[10000];
    new Random().nextBytes(content2);
    bodyPart2.setDataHandler(new DataHandler(new ByteArrayDataSource(content2, "application/octet-stream")));
    Map<String, String> headers2 = new HashMap<String, String>();
    headers2.put("Content-ID", "<2@example.com>");
    headers2.put("Content-Type", "application/octet-stream");
    setHeaders(bodyPart2, headers2);
    multipart.addBodyPart(bodyPart2);

    if (preamble) {
        multipart.setPreamble("This is a MIME multipart.");
    }

    String boundary = new ContentType(multipart.getContentType()).getParameter("boundary");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    multipart.writeTo(baos);
    MultipartReader mpr = new MultipartReader(new ByteArrayInputStream(baos.toByteArray()), boundary);
    assertTrue(mpr.nextPart());
    assertEquals(headers1, readHeaders(mpr));
    assertEquals(content1, IOUtils.toString(mpr.getContent(), "UTF-8"));
    assertTrue(mpr.nextPart());
    assertEquals(headers2, readHeaders(mpr));
    assertArrayEquals(content2, IOUtils.toByteArray(mpr.getContent()));
    assertFalse(mpr.nextPart());
}

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

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

        if (authenticate) {
            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, fromName));
        } 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 (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

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

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

        Transport.send(msg);

        return true;
    } 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.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }/*from w w w  .  ja v  a 2 s  .  c  om*/

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

From source file:org.openmrs.module.reporting.report.processor.EmailReportProcessor.java

/**
 * Performs some action on the given report
 * @param report the Report to process//  www .j a  v a  2s .  c  o m
 */
public void process(Report report, Properties configuration) {

    try {
        Message m = new MimeMessage(getSession());

        m.setFrom(new InternetAddress(configuration.getProperty("from")));
        for (String recipient : configuration.getProperty("to", "").split("\\,")) {
            m.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        // TODO: Make these such that they can contain report information
        m.setSubject(configuration.getProperty("subject"));

        Multipart multipart = new MimeMultipart();

        MimeBodyPart contentBodyPart = new MimeBodyPart();
        String content = configuration.getProperty("content", "");
        if (report.getRenderedOutput() != null
                && "true".equalsIgnoreCase(configuration.getProperty("addOutputToContent"))) {
            content += new String(report.getRenderedOutput());
        }
        contentBodyPart.setContent(content, "text/html");
        multipart.addBodyPart(contentBodyPart);

        if (report.getRenderedOutput() != null
                && "true".equalsIgnoreCase(configuration.getProperty("addOutputAsAttachment"))) {
            MimeBodyPart attachment = new MimeBodyPart();
            Object output = report.getRenderedOutput();
            if (report.getOutputContentType().contains("text")) {
                output = new String(report.getRenderedOutput(), "UTF-8");
            }
            attachment.setDataHandler(new DataHandler(output, report.getOutputContentType()));
            attachment.setFileName(configuration.getProperty("attachmentName"));
            multipart.addBodyPart(attachment);
        }

        m.setContent(multipart);

        Transport.send(m);
    } catch (Exception e) {
        throw new RuntimeException("Error occurred while sending report over email", e);
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

/**
 * Creates root BodyPart containing message
 *///from  ww  w.  ja v  a  2  s . c om

protected void initRootPart(WsdlRequest wsdlRequest, String requestContent, MimeMultipart mp, boolean isXOP)
        throws MessagingException {
    MimeBodyPart rootPart = new PreencodedMimeBodyPart(System.getProperty("soapui.bodypart.encoding", "8bit"));
    rootPart.setContentID(AttachmentUtils.ROOTPART_SOAPUI_ORG);
    mp.addBodyPart(rootPart, 0);

    DataHandler dataHandler = new DataHandler(new WsdlRequestDataSource(wsdlRequest, requestContent, isXOP));
    rootPart.setDataHandler(dataHandler);
}

From source file:com.zotoh.crypto.CryptoUte.java

/**
 * @param contentType/*www.jav  a2s. c o  m*/
 * @param msg
 * @return
 * @throws IOException
 * @throws MessagingException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(String contentType, StreamData msg)
        throws IOException, MessagingException, GeneralSecurityException {

    tstEStrArg("content-type", contentType);
    tstObjArg("input-content", msg);

    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();
    MimeBodyPart bp = new MimeBodyPart();
    SmDataSource ds;

    if (msg.isDiskFile()) {
        ds = new SmDataSource(msg.getFileRef(), contentType);
    } else {
        ds = new SmDataSource(msg.getBytes(), contentType);
    }

    bp.setDataHandler(new DataHandler(ds));
    try {
        return gen.generate(bp, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:org.apache.axis.attachments.MimeUtils.java

/**
 * This routine will create a multipart object from the parts and the SOAP content.
 * @param env should be the text for the main root part.
 * @param parts contain a collection of the message parts.
 *
 * @return a new MimeMultipart object/*from   ww w  .j  av  a2  s .c  o  m*/
 *
 * @throws org.apache.axis.AxisFault
 */
public static javax.mail.internet.MimeMultipart createMP(String env, java.util.Collection parts, int sendType)
        throws org.apache.axis.AxisFault {

    javax.mail.internet.MimeMultipart multipart = null;

    try {
        String rootCID = SessionUtils.generateSessionId();

        if (sendType == Attachments.SEND_TYPE_MTOM) {
            multipart = new javax.mail.internet.MimeMultipart("related;type=\"application/xop+xml\"; start=\"<"
                    + rootCID + ">\"; start-info=\"text/xml; charset=utf-8\"");
        } else {
            multipart = new javax.mail.internet.MimeMultipart(
                    "related; type=\"text/xml\"; start=\"<" + rootCID + ">\"");
        }

        javax.mail.internet.MimeBodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        messageBodyPart.setText(env, "UTF-8");
        if (sendType == Attachments.SEND_TYPE_MTOM) {
            messageBodyPart.setHeader("Content-Type",
                    "application/xop+xml; charset=utf-8; type=\"text/xml; charset=utf-8\"");
        } else {
            messageBodyPart.setHeader("Content-Type", "text/xml; charset=UTF-8");
        }
        messageBodyPart.setHeader("Content-Id", "<" + rootCID + ">");
        messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary");
        multipart.addBodyPart(messageBodyPart);

        for (java.util.Iterator it = parts.iterator(); it.hasNext();) {
            org.apache.axis.Part part = (org.apache.axis.Part) it.next();
            javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils
                    .getActivationDataHandler(part);
            String contentID = part.getContentId();

            messageBodyPart = new javax.mail.internet.MimeBodyPart();

            messageBodyPart.setDataHandler(dh);

            String contentType = part.getContentType();
            if ((contentType == null) || (contentType.trim().length() == 0)) {
                contentType = dh.getContentType();
            }
            if ((contentType == null) || (contentType.trim().length() == 0)) {
                contentType = "application/octet-stream";
            }

            messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, contentType);
            messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_ID, "<" + contentID + ">");
            messageBodyPart.setHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, "binary"); // Safe and fastest for anything other than mail;

            for (java.util.Iterator i = part.getNonMatchingMimeHeaders(
                    new String[] { HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.HEADER_CONTENT_ID,
                            HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING }); i.hasNext();) {
                javax.xml.soap.MimeHeader header = (javax.xml.soap.MimeHeader) i.next();

                messageBodyPart.setHeader(header.getName(), header.getValue());
            }

            multipart.addBodyPart(messageBodyPart);
        }
    } catch (javax.mail.MessagingException e) {
        log.error(Messages.getMessage("javaxMailMessagingException00"), e);
    }

    return multipart;
}