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:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/* w  w  w  . j  a v a2 s  . c  o m*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject)
        throws MessagingException, IOException {
    MimeMessage message = prepareMimeMessage(subject);
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8")));
    scriptPart.setDisposition(MimeBodyPart.ATTACHMENT);
    // setting a DataHandler with no mailcap definition is not
    // supported by the specs. Javamail activation still work,
    // but Geronimo activation translate it to text/plain.
    // Let's manually force the header.
    scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8");
    scriptPart.setFileName(SCRIPT_NAME);
    multipart.addBodyPart(scriptPart);//from  w  w w  .ja va2 s  .com
    message.setContent(multipart);
    message.saveChanges();
    return message;
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*from   ww w.  jav  a  2 s .  c o m*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:com.openkm.util.MailUtils.java

/**
 * Create a mail./*from w  w  w.ja  v  a  2  s  . co  m*/
 * 
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param subject The mail subject.
 * @param text The mail body.
 * @throws MessagingException If there is any error.
 */
private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text,
        Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException,
        PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath });
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (fromAddress != null && Config.SEND_MAIL_FROM_USER) {
        InternetAddress from = new InternetAddress(fromAddress);
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[toAddress.size()];
    int idx = 0;

    for (Iterator<String> it = toAddress.iterator(); it.hasNext();) {
        to[idx++] = new InternetAddress(it.next());
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    Multipart content = new MimeMultipart();

    // HTML Part
    MimeBodyPart htmlPart = new MimeBodyPart();
    StringBuilder htmlContent = new StringBuilder();
    htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
    htmlContent.append("<html>\n<head>\n");
    htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
    htmlContent.append("</head>\n<body>\n");
    htmlContent.append(text);
    htmlContent.append("\n</body>\n</html>");
    htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8");
    htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8");
    htmlPart.setDisposition(Part.INLINE);
    content.addBodyPart(htmlPart);
    idx = 0;

    if (docsPath != null) {
        for (String docPath : docsPath) {
            InputStream is = null;
            FileOutputStream fos = null;
            String docName = PathUtils.getName(docPath);

            try {
                final Document doc = OKMDocument.getInstance().getProperties(null, docPath);
                is = OKMDocument.getInstance().getContent(null, docPath, false);
                final File tmpAttch = tmpAttachments.get(idx++);
                fos = new FileOutputStream(tmpAttch);
                IOUtils.copy(is, fos);
                fos.flush();

                // Document attachment part
                MimeBodyPart docPart = new MimeBodyPart();
                DataSource source = new FileDataSource(tmpAttch.getPath()) {
                    public String getContentType() {
                        return doc.getMimeType();
                    }
                };

                docPart.setDataHandler(new DataHandler(source));
                docPart.setFileName(MimeUtility.encodeText(docName));
                docPart.setDisposition(Part.ATTACHMENT);
                content.addBodyPart(docPart);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*from  w  ww. j a v a 2 s  .  co  m*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.igov.io.mail.Mail.java

public Mail _Attach(URL oURL, String sName) {
    try {//  w  ww .  jav  a 2 s .  c  o  m
        MimeBodyPart oMimeBodyPart = new MimeBodyPart();//javax.activation
        oMimeBodyPart.setHeader("Content-Type", "multipart/mixed");
        DataSource oDataSource = new URLDataSource(oURL);
        oMimeBodyPart.setDataHandler(new DataHandler(oDataSource));
        //oPart.setFileName(MimeUtility.encodeText(source.getName()));
        oMimeBodyPart.setFileName(
                MimeUtility.encodeText(sName == null || "".equals(sName) ? oDataSource.getName() : sName));
        oMultiparts.addBodyPart(oMimeBodyPart);
        LOG.info("(sName={})", sName);
    } catch (Exception oException) {
        LOG.error("FAIL: {} (sName={})", oException.getMessage(), sName);
        LOG.trace("FAIL:", oException);
    }
    return this;
}

From source file:org.apache.synapse.transport.mail.MailTransportSender.java

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error//from ww  w. j  av  a  2  s. co m
 */
private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    MessageFormatter messageFormatter = null;

    try {
        messageFormatter = TransportUtils.getMessageFormatter(msgContext);
    } catch (AxisFault axisFault) {
        throw new BaseTransportException("Unable to get the message formatter to use");
    }

    WSMimeMessage message = new WSMimeMessage(session);
    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)));
        message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)));
    } else {
        if (smtpFromAddress != null) {
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO)));
    } else if (outInfo.getTargetAddresses() != null) {
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        message.setRecipients(Message.RecipientType.CC,
                InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC)));
    } else if (outInfo.getTargetAddresses() != null) {
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    InternetAddress[] trpBccArr = null;
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
    }

    InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0)
            + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)];
    if (trpBccArr != null) {
        System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length);
    }
    if (smtpBccAddresses != null) {
        System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length);
    }
    if (mergedBcc != null) {
        message.setRecipients(Message.RecipientType.BCC, mergedBcc);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        message.setSubject(outInfo.getSubject());
    } else {
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    // if a custom message id is set, use it
    if (msgContext.getMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    ByteArrayOutputStream baos = null;
    String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());
    DataHandler dataHandler = null;
    MimeMultipart mimeMultiPart = null;

    OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement();
    if (firstChild != null) {

        if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) {
            baos = new ByteArrayOutputStream();
            OMNode omNode = firstChild.getFirstOMChild();

            if (omNode != null && omNode instanceof OMText) {
                Object dh = ((OMText) omNode).getDataHandler();
                if (dh != null && dh instanceof DataHandler) {
                    dataHandler = (DataHandler) dh;
                }
            }
        } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) {
            if (firstChild instanceof OMSourcedElementImpl) {
                baos = new ByteArrayOutputStream();
                try {
                    firstChild.serializeAndConsume(baos);
                } catch (XMLStreamException e) {
                    handleException("Error serializing 'text' payload from OMSourcedElement", e);
                }
                dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()),
                        MailConstants.TEXT_PLAIN);
            } else {
                dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN);
            }
        } else {

            baos = new ByteArrayOutputStream();
            messageFormatter.writeTo(msgContext, format, baos, true);

            // create the data handler
            dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()),
                    contentType);

            String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
            if (mFormat == null) {
                mFormat = defaultMailFormat;
            }

            if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
                mimeMultiPart = new MimeMultipart();
                MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
                mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
                MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
                mimeBodyPart2.setDataHandler(dataHandler);
                mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
                mimeMultiPart.addBodyPart(mimeBodyPart1);
                mimeMultiPart.addBodyPart(mimeBodyPart2);

            } else {
                message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
            }
        }
    }

    try {
        if (mimeMultiPart == null) {
            message.setDataHandler(dataHandler);
        } else {
            message.setContent(mimeMultiPart);
        }
        Transport.send(message);

    } catch (MessagingException e) {
        handleException("Error creating mail message or sending it to the configured server", e);

    } finally {
        try {
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public void addAttachement(File file) {
    try {/*from   www  .j  a  v  a 2 s  .co  m*/
        /* Check if email has already some contents. */
        Object content;
        try {
            content = this.source.getContent();
        } catch (IOException e) {
            /* If no content, then content is null.*/
            content = null;
            log.warn("Email content is empty.", e);
        }
        if (content != null) {
            if (content instanceof String) {
                /* This message is not multipart yet. Change it to multipart. */
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText((String) this.source.getContent());

                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messageBodyPart);
                this.source.setContent(multipart);
            }
        } else {
            /* No content, then create initial multipart content. */
            Multipart multipart = new MimeMultipart();
            this.source.setContent(multipart);
        }

        /* Get current content. */
        Multipart multipart = (Multipart) this.source.getContent();
        /* add attachment as a new part. */
        MimeBodyPart attachementPart = new MimeBodyPart();
        DataSource fileSource = new FileDataSource(file);
        DataHandler fileDataHandler = new DataHandler(fileSource);
        attachementPart.setDataHandler(fileDataHandler);
        attachementPart.setFileName(file.getName());
        multipart.addBodyPart(attachementPart);
    } catch (Exception e) {
        throw new GmailException("Failed to add attachement", e);
    }
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private void processSpecificAttachment(final MimeMultipart mixedMultipart, final IContentItem attachmentContent)
        throws IOException, MessagingException {

    // Add this attachment

    if (attachmentContent != null) {

        final ByteArrayDataSource dataSource = new ByteArrayDataSource(attachmentContent.getInputStream(),
                attachmentContent.getMimeType());
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(getAttachmentName());
        mixedMultipart.addBodyPart(attachmentBodyPart);

    }/*from  w  w w  .ja va2 s . co m*/

}

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

/**
 * @param cType// w  ww  . j av a 2s. c  om
 * @param cte
 * @param contentLoc
 * @param cid
 * @param msg
 * @return
 * @throws MessagingException
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static MimeBodyPart compressContent(String cType, String cte, String contentLoc, String cid,
        StreamData msg) throws MessagingException, IOException, GeneralSecurityException {

    tstEStrArg("content-type", cType);
    tstEStrArg("content-id", cid);
    tstObjArg("input-content", msg);

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

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

    if (!isEmpty(contentLoc)) {
        bp.setHeader("content-location", contentLoc);
    }

    try {
        bp.setHeader("content-id", cid);
        bp.setDataHandler(new DataHandler(ds));
        bp = gen.generate(bp, SMIMECompressedGenerator.ZLIB);
    } catch (SMIMEException e) {
        throw new GeneralSecurityException(e);
    }

    if (true) {
        int pos = cid.lastIndexOf(">");
        if (pos >= 0) {
            cid = cid.substring(0, pos) + "--z>";
        } else {
            cid = cid + "--z";
        }
    }

    if (!isEmpty(contentLoc)) {
        bp.setHeader("content-location", contentLoc);
    }
    bp.setHeader("content-id", cid);

    // always base64
    cte = "base64";

    if (!isEmpty(cte)) {
        bp.setHeader("content-transfer-encoding", cte);
    }

    return bp;
}