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:com.panet.imeta.trans.steps.mail.Mail.java

private void addAttachedFilePart(FileObject file) throws Exception {
    // create a data source

    MimeBodyPart files = new MimeBodyPart();
    // create a data source
    URLDataSource fds = new URLDataSource(file.getURL());
    // get a data Handler to manipulate this file type;
    files.setDataHandler(new DataHandler(fds));
    // include the file in the data source
    files.setFileName(file.getName().getBaseName());
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(files);/*w w  w  .  j  ava2  s. c o  m*/
    if (log.isDetailed())
        log.logDetailed(toString(), Messages.getString("Mail.Log.AttachedFile", fds.getName()));

}

From source file:lucee.runtime.net.smtp.SMTPClient.java

private BodyPart toMimeBodyPart(MailPart part) throws MessagingException {
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setDataHandler(
            new DataHandler(new StringDataSource(part.getBody(), part.getType(), part.getCharset(), 980)));
    //mbp.setHeader("Content-Transfer-Encoding", "7bit");
    //mbp.setHeader("Content-Type", TEXT_PLAIN+"; charset="+plainTextCharset);
    return mbp;/* w w w  . jav a  2  s  .c om*/
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Builds up a new message from the passed message parts
 * @param messageType one of the message types definfed in the class AS2Message
 *//* w  w  w  .  j  av  a 2s .c om*/
public AS2Message createMessage(Partner sender, Partner receiver, AS2Payload[] payloads, int messageType,
        String messageId) throws Exception {
    if (messageId == null) {
        messageId = UniqueId.createMessageId(sender.getAS2Identification(), receiver.getAS2Identification());
    }
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    AS2MessageInfo info = new AS2MessageInfo();
    info.setMessageType(messageType);
    info.setSenderId(sender.getAS2Identification());
    info.setReceiverId(receiver.getAS2Identification());
    info.setSenderEMail(sender.getEmail());
    info.setMessageId(messageId);
    info.setDirection(AS2MessageInfo.DIRECTION_OUT);
    info.setSignType(receiver.getSignType());
    info.setEncryptionType(receiver.getEncryptionType());
    info.setRequestsSyncMDN(receiver.isSyncMDN());
    if (!receiver.isSyncMDN()) {
        info.setAsyncMDNURL(sender.getMdnURL());
    }
    info.setSubject(receiver.getSubject());
    try {
        info.setSenderHost(InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        //nop
    }
    //create message object to return
    AS2Message message = new AS2Message(info);
    //stores all the available body parts that have been prepared
    List<MimeBodyPart> contentPartList = new ArrayList<MimeBodyPart>();
    for (AS2Payload as2Payload : payloads) {
        //add payload
        message.addPayload(as2Payload);
        if (this.runtimeConnection != null) {
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            messageAccess.initializeOrUpdateMessage(info);
        }
        //no MIME message: single payload, unsigned, no CEM
        if (info.getSignType() == AS2Message.SIGNATURE_NONE && payloads.length == 1
                && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
            return (this.createMessageNoMIME(message, receiver));
        }
        //MIME message
        MimeBodyPart bodyPart = new MimeBodyPart();
        String contentType = null;
        if (as2Payload.getContentType() == null) {
            contentType = receiver.getContentType();
        } else {
            contentType = as2Payload.getContentType();
        }
        bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(as2Payload.getData(), contentType)));
        bodyPart.addHeader("Content-Type", contentType);
        if (as2Payload.getContentId() != null) {
            bodyPart.addHeader("Content-ID", as2Payload.getContentId());
        }
        if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) {
            bodyPart.addHeader("Content-Transfer-Encoding", "base64");
        } else {
            bodyPart.addHeader("Content-Transfer-Encoding", "binary");
        }
        //prepare filename to not violate the MIME header rules
        if (as2Payload.getOriginalFilename() == null) {
            as2Payload.setOriginalFilename(new File(as2Payload.getPayloadFilename()).getName());
        }
        String newFilename = as2Payload.getOriginalFilename().replace(' ', '_');
        newFilename = newFilename.replace('@', '_');
        newFilename = newFilename.replace(':', '_');
        newFilename = newFilename.replace(';', '_');
        newFilename = newFilename.replace('(', '_');
        newFilename = newFilename.replace(')', '_');
        bodyPart.addHeader("Content-Disposition", "attachment; filename=" + newFilename);
        contentPartList.add(bodyPart);
    }
    Part contentPart = null;
    //sigle attachment? No CEM? Every CEM is in a multipart/related container
    if (contentPartList.size() == 1 && info.getMessageType() != AS2Message.MESSAGETYPE_CEM) {
        contentPart = contentPartList.get(0);
    } else {
        //build up a new MimeMultipart container for the multiple attachments, content-type
        //is "multipart/related"
        MimeMultipart multipart = null;
        //CEM messages are always in a multipart container (even the response which contains only a single
        //payload) with the subtype "application/ediint-cert-exchange+xml".
        if (info.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
            multipart = new MimeMultipart("related; type=\"application/ediint-cert-exchange+xml\"");
        } else {
            multipart = new MimeMultipart("related");
        }
        for (MimeBodyPart bodyPart : contentPartList) {
            multipart.addBodyPart(bodyPart);
        }
        contentPart = new MimeMessage(Session.getInstance(System.getProperties(), null));
        contentPart.setContent(multipart, multipart.getContentType());
        ((MimeMessage) contentPart).saveChanges();
    }
    //should the content be compressed and enwrapped or just enwrapped?
    if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) {
        info.setCompressionType(AS2Message.COMPRESSION_ZLIB);
        int uncompressedSize = contentPart.getSize();
        contentPart = this.compressPayload(receiver, contentPart);
        int compressedSize = contentPart.getSize();
        //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the
        //compression ratio in this case.
        if (uncompressedSize == -1 || compressedSize == -1) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio",
                        new Object[] { info.getMessageId() }), info);
            }
        } else {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.compressed",
                                new Object[] { info.getMessageId(),
                                        AS2Tools.getDataSizeDisplay(uncompressedSize),
                                        AS2Tools.getDataSizeDisplay(compressedSize) }),
                        info);
            }
        }
    }
    //compute content mic. Try to use sign digest as hash alg. For unsigned messages take sha-1
    String digestOID = null;
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_MD5);
    } else {
        digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    }
    String mic = cryptoHelper.calculateMIC(contentPart, digestOID);
    if (info.getSignType() == AS2Message.SIGNATURE_MD5) {
        info.setReceivedContentMIC(mic + ", md5");
    } else {
        info.setReceivedContentMIC(mic + ", sha1");
    }
    this.enwrappInMessageAndSign(message, contentPart, sender, receiver);
    //encryption requested for the receiver?
    if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver);
    } else {
        message.setRawData(message.getDecryptedRawData());
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }),
                    info);
        }
    }
    return (message);
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

private void addAttachedContent(String filename, String fileContent) throws Exception {
    // create a data source

    MimeBodyPart mbp = new MimeBodyPart();
    // get a data Handler to manipulate this file type;
    mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(fileContent.getBytes(), "application/x-any")));
    // include the file in the data source
    mbp.setFileName(filename);/* ww w.  j  a  va2  s . c om*/
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(mbp);

}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*w ww.  j  a v a  2s  .  com*/
 *
 * @param multipart DOCUMENT ME!
 * @param file DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException {
    // UNDONE how to specify the character set of the file???
    MimeBodyPart xbody = new MimeBodyPart();
    FileDataSource xds = new FileDataSource(file);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    //System.out.println(xdh.getContentType());
    // UNDONE
    // xbody.setContentLanguage( String ); // this could be language from Locale
    // xbody.setContentMD5( String md5 ); // don't know about this yet
    xbody.setDescription("File Attachment: " + file.getName(), charset);
    xbody.setDisposition(Part.ATTACHMENT);
    MessageUtilities.setFileName(xbody, file.getName(), charset);

    multipart.addBodyPart(xbody);
}

From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java

public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) {
    String host = "smtp.gmail.com";
    message = "Some of the appliances in your house are running inefficient." + "\n"
            + "Kindly check or replace your appliance " + "\n"
            + "Check the attachment for details or visit your account";
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", 587);
    props.put("mail.smtp.user", from);

    Session session = Session.getDefaultInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {/*w ww. j  a v  a  2  s  .  c  om*/
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        mimeMessage.setSubject("Alert from Energy Board");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(name_attach.getText() + ".png");
        multipart.addBodyPart(messageBodyPart);
        mimeMessage.setContent(multipart);

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtps");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        System.out.println("sent");
        transport.close();
    } catch (MessagingException me) {

    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java

private MimeBodyPart zipAttachment(byte[] attach, String containedFileName, String zipFileName,
        String nameSuffix, String fileExtension) {
    MimeBodyPart messageBodyPart = null;
    try {/*  w  w  w  . j  a v  a  2s  .  c  o m*/

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(bout);
        String entryName = containedFileName + nameSuffix + fileExtension;
        zipOut.putNextEntry(new ZipEntry(entryName));
        zipOut.write(attach);
        zipOut.closeEntry();

        zipOut.close();

        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip");

    } catch (Exception e) {
        // TODO: handle exception            
    }
    return messageBodyPart;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from   w w  w. j a va 2 s. c om*/
 *
 * @param multipart DOCUMENT ME!
 * @param part DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException {
    MimeBodyPart xbody = new MimeBodyPart();
    PartDataSource xds = new PartDataSource(part);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    int xid = multipart.getCount() + 1;
    String xtext;

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet
    xtext = part.getDescription();

    if (xtext == null) {
        xtext = "Part Attachment: " + xid;
    }

    xbody.setDescription(xtext, charset);

    xtext = getContentDisposition(part).getType();
    xbody.setDisposition(xtext);

    xtext = MessageUtilities.getFileName(part);

    if ((xtext == null) || (xtext.length() < 1)) {
        xtext = "PART" + xid;
    }

    MessageUtilities.setFileName(xbody, xtext, charset);

    multipart.addBodyPart(xbody);
}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }/*from  w  w  w. j  a  va 2s . com*/
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}