Java 类javax.mail.BodyPart 实例源码

项目:Cognizant-Intelligent-Test-Scripter    文件:Mailer.java   
private static Multipart getMessagePart() throws MessagingException, IOException {
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(getVal("msg.Body"));
    multipart.addBodyPart(messageBodyPart);
    if (getBoolVal("attach.reports")) {
        LOG.info("Attaching Reports as zip");
        multipart.addBodyPart(getReportsBodyPart());
    } else {
        if (getBoolVal("attach.standaloneHtml")) {
            multipart.addBodyPart(getStandaloneHtmlBodyPart());
        }
        if (getBoolVal("attach.console")) {
            multipart.addBodyPart(getConsoleBodyPart());
        }
        if (getBoolVal("attach.screenshots")) {
            multipart.addBodyPart(getScreenShotsBodyPart());
        }
    }
    messageBodyPart.setContent(getVal("msg.Body")
            .concat("\n\n\n")
            .concat(MailComponent.getHTMLBody()), "text/html");
    return multipart;
}
项目:opentest    文件:ReadEmailImap.java   
/**
 * Extracts the text content of a multipart email message
 */
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws Exception {
    String result = "";
    int partCount = mimeMultipart.getCount();
    for (int i = 0; i < partCount; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result = result + "\n" + bodyPart.getContent();
            break; // without break same text appears twice in my tests
        } else if (bodyPart.isMimeType("text/html")) {
            String html = (String) bodyPart.getContent();
            // result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
            result = html;
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result = result + getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
        }
    }
    return result;
}
项目:jsf-core    文件:ReciveMail.java   
/**   
 * 【保存附件】   
 */   
public void saveAttachMent(Part part) throws Exception {   
    String fileName = "";   
    if (part.isMimeType("multipart/*")) {   
        Multipart mp = (Multipart) part.getContent();   
        for (int i = 0; i < mp.getCount(); i++) {   
            BodyPart mpart = mp.getBodyPart(i);   
            String disposition = mpart.getDisposition();   
            if ((disposition != null)   
                    && ((disposition.equals(Part.ATTACHMENT)) || (disposition   
                            .equals(Part.INLINE)))) {   
                fileName = mpart.getFileName();   
                if (fileName.toLowerCase().indexOf("gb2312") != -1) {   
                    fileName = MimeUtility.decodeText(fileName);   
                }   
                saveFile(fileName, mpart.getInputStream());   
            } else if (mpart.isMimeType("multipart/*")) {   
                saveAttachMent(mpart);   
            } else {   
                fileName = mpart.getFileName();   
                if ((fileName != null)   
                        && (fileName.toLowerCase().indexOf("GB2312") != -1)) {   
                    fileName = MimeUtility.decodeText(fileName);   
                    saveFile(fileName, mpart.getInputStream());   
                }   
            }   
        }   
    } else if (part.isMimeType("message/rfc822")) {   
        saveAttachMent((Part) part.getContent());   
    }   
}
项目:Camel    文件:MailConverters.java   
/**
 * Converts the given JavaMail message to a String body.
 * Can return null.
 */
@Converter
public static String toString(Message message) throws MessagingException, IOException {
    Object content = message.getContent();
    if (content instanceof MimeMultipart) {
        MimeMultipart multipart = (MimeMultipart) content;
        if (multipart.getCount() > 0) {
            BodyPart part = multipart.getBodyPart(0);
            content = part.getContent();
        }
    }
    if (content != null) {
        return content.toString();
    }
    return null;
}
项目:play    文件:MailHelper.java   
/**
 * ������
 */
private void handleAttachments(Message message, Part part) throws Exception {
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            String disposition = bp.getDisposition();
            if (disposition != null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
                saveFile(message, bp);
            } else if (bp.isMimeType("multipart/*")) {
                handleAttachments(message, (Part) part.getContent());
            } else {
                saveFile(message, bp);
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        handleAttachments(message, (Part) part.getContent());
    }
}
项目:ats-framework    文件:MimePackage.java   
/**
 * Check if the body is from the content type and returns it if not attachment
 *
 * @param mimePart
 * @param contentType
 * @return null if not with specific content type or part is attachment
 */
private String getBodyIfNotAttachment(
                                       BodyPart mimePart,
                                       String contentType ) throws MessagingException, IOException {

    String mimePartContentType = mimePart.getContentType().toLowerCase();
    if (mimePartContentType.startsWith(contentType)) { // found a part with given mime type
        String contentDisposition = mimePart.getDisposition();
        if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) {
            Object partContent = mimePart.getContent();
            if (partContent instanceof InputStream) {
                return IoUtils.streamToString((InputStream) partContent);
            } else {
                return partContent.toString();
            }
        }
    }
    return null;
}
项目:lemon    文件:JavamailService.java   
public void getMailTextContent(Part part, StringBuffer content)
        throws MessagingException, IOException {
    // 如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;

    if (part.isMimeType("text/*") && !isContainTextAttach) {
        content.append(part.getContent().toString());
    } else if (part.isMimeType("message/rfc822")) {
        getMailTextContent((Part) part.getContent(), content);
    } else if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int partCount = multipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            getMailTextContent(bodyPart, content);
        }
    }
}
项目:fake-smtp-server    文件:EmailFactory.java   
private Email buildMultipartAlternativeMail(RawData rawData, String subject, Multipart multipart) throws MessagingException, IOException {
    Email email = null;
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart part = multipart.getBodyPart(i);
        ContentType partContentType = ContentType.fromString(part.getContentType());
        Object partContent = part.getContent();
        email = new Email.Builder()
                .fromAddress(rawData.getFrom())
                .toAddress(rawData.getTo())
                .receivedOn(timestampProvider.now())
                .subject(subject)
                .rawData(rawData.getContentAsString())
                .content(Objects.toString(partContent, rawData.getContentAsString()).trim())
                .contentType(partContentType)
                .build();
        if (partContentType == ContentType.HTML) break;
    }
    return email;
}
项目:jsf-core    文件:ReciveMail.java   
/**  
 * 判断此邮件是否包含附件  
 */  
public boolean isContainAttach(Part part) throws Exception {   
    boolean attachflag = false;   
    String contentType = part.getContentType();   
    if (part.isMimeType("multipart/*")) {   
        Multipart mp = (Multipart) part.getContent();   
        for (int i = 0; i < mp.getCount(); i++) {   
            BodyPart mpart = mp.getBodyPart(i);   
            String disposition = mpart.getDisposition();   
            if ((disposition != null)   
                    && ((disposition.equals(Part.ATTACHMENT)) || (disposition   
                            .equals(Part.INLINE))))   
                attachflag = true;   
            else if (mpart.isMimeType("multipart/*")) {   
                attachflag = isContainAttach((Part) mpart);   
            } else {   
                String contype = mpart.getContentType();   
                if (contype.toLowerCase().indexOf("application") != -1)   
                    attachflag = true;   
                if (contype.toLowerCase().indexOf("name") != -1)   
                    attachflag = true;   
            }   
        }   
    } else if (part.isMimeType("message/rfc822")) {   
        attachflag = isContainAttach((Part) part.getContent());   
    }   
    return attachflag;   
}
项目:infotaf    文件:Utils.java   
/**
 * Récupération d'une pièce jointe d'un mail
 * @param part : Corps du mail (Bodypart)
 * @return
 * @throws Exception
 */
private static Map<String, InputStream> getAttachments(BodyPart part) throws Exception {
    Map<String, InputStream> result = new HashMap<String, InputStream>();
    Object content = part.getContent();
    if (content instanceof InputStream || content instanceof String) {
        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) {
            result.put(part.getFileName(), part.getInputStream());
            return result;
        } else {
            return new HashMap<String, InputStream>();
        }
    }

    if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                result.putAll(getAttachments(bodyPart));
            }
    }
    return result;
}
项目:scipio-erp    文件:ServiceMcaCondition.java   
private List<String> getBodyText(Part part) throws MessagingException, IOException {
    Object c = part.getContent();
    if (c instanceof String) {
        return UtilMisc.toList((String) c);
    } else if (c instanceof Multipart) {
        List<String> textContent = new LinkedList<String>();
        int count = ((Multipart) c).getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bp = ((Multipart) c).getBodyPart(i);
            textContent.addAll(this.getBodyText(bp));
        }
        return textContent;
    } else {
        return new LinkedList<String>();
    }
}
项目:thatsapp    文件:MailUtilities.java   
private static TreeMap<String, InputStream> getAttachments(BodyPart part) throws Exception {
    TreeMap<String, InputStream> result = new TreeMap<>();
    Object content = part.getContent();
    if (content instanceof InputStream || content instanceof String) {
        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) {
            result.put(part.getFileName(), part.getInputStream());
            return result;
        } else {
            return new TreeMap<String, InputStream>();
        }
    }

    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            result.putAll(getAttachments(bodyPart));
        }
    }
    return result;
}
项目:anti-spam-weka-gui    文件:MailHelper.java   
private static Message buildMessage(Session session, String from, String recipients, String subject, String text, String filename) throws MessagingException, AddressException
{
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
    message.setSubject(subject);

    BodyPart messageTextPart = new MimeBodyPart();
    messageTextPart.setText(text);

    BodyPart messageAttachmentPart = new MimeBodyPart();
    DataSource source = new FileDataSource(new File(filename));
    messageAttachmentPart.setDataHandler(new DataHandler(source));
    messageAttachmentPart.setFileName(filename);

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageTextPart);
    multipart.addBodyPart(messageAttachmentPart);
    message.setContent(multipart);

    return message;
}
项目:camunda-bpm-mail    文件:Mail.java   
protected static void processMessageContent(Message message, Mail mail) throws MessagingException, IOException {

    if (isMultipartMessage(message)) {
      Multipart multipart = (Multipart) message.getContent();

      int numberOfParts = multipart.getCount();
      for (int partCount = 0; partCount < numberOfParts; partCount++) {
        BodyPart bodyPart = multipart.getBodyPart(partCount);

        processMessagePartContent(bodyPart, mail);
      }

    } else {
      processMessagePartContent(message, mail);
    }
  }
项目:scada    文件:MailUtils.java   
/**
 * �ж��ʼ����Ƿ��������
 * @param msg �ʼ�����
 * @return �ʼ��д��ڸ�������true�������ڷ���false
 */ 
public static boolean isContainAttachment(Part part) throws MessagingException, IOException { 
    boolean flag = false; 
    if (part.isMimeType("multipart/*")) { 
        MimeMultipart multipart = (MimeMultipart) part.getContent(); 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            String disp = bodyPart.getDisposition(); 
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
                flag = true; 
            } else if (bodyPart.isMimeType("multipart/*")) { 
                flag = isContainAttachment(bodyPart); 
            } else { 
                String contentType = bodyPart.getContentType(); 
                if (contentType.indexOf("application") != -1) { 
                    flag = true; 
                }   

                if (contentType.indexOf("name") != -1) { 
                    flag = true; 
                }  
            } 

            if (flag) break; 
        } 
    } else if (part.isMimeType("message/rfc822")) { 
        flag = isContainAttachment((Part)part.getContent()); 
    } 
    return flag; 
}
项目:scada    文件:MailUtils.java   
/** 
 * ���渽�� 
 * @param part �ʼ��ж��������е�����һ������� 
 * @param destDir  ��������Ŀ¼ 
 */ 
public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, 
        FileNotFoundException, IOException { 
    if (part.isMimeType("multipart/*")) { 
        Multipart multipart = (Multipart) part.getContent();    //�������ʼ� 
        //�������ʼ���������ʼ��� 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            //��ø������ʼ�������һ���ʼ��� 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            //ijһ���ʼ���Ҳ�п������ɶ���ʼ�����ɵĸ����� 
            String disp = bodyPart.getDisposition(); 
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
                InputStream is = bodyPart.getInputStream(); 
                saveFile(is, destDir, decodeText(bodyPart.getFileName())); 
            } else if (bodyPart.isMimeType("multipart/*")) { 
                saveAttachment(bodyPart,destDir); 
            } else { 
                String contentType = bodyPart.getContentType(); 
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { 
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); 
                } 
            } 
        } 
    } else if (part.isMimeType("message/rfc822")) { 
        saveAttachment((Part) part.getContent(),destDir); 
    } 
}
项目:alimama    文件:POP3ReceiveMailTest.java   
/**
 * 判断邮件中是否包含附件
 * @param msg 邮件内容
 * @return 邮件中存在附件返回true,不存在返回false
 * @throws MessagingException
 * @throws IOException
 */
public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
    boolean flag = false;
    if (part.isMimeType("multipart/*")) {
        MimeMultipart multipart = (MimeMultipart) part.getContent();
        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            String disp = bodyPart.getDisposition();
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                flag = true;
            } else if (bodyPart.isMimeType("multipart/*")) {
                flag = isContainAttachment(bodyPart);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("application") != -1) {
                    flag = true;
                }  

                if (contentType.indexOf("name") != -1) {
                    flag = true;
                } 
            }

            if (flag) break;
        }
    } else if (part.isMimeType("message/rfc822")) {
        flag = isContainAttachment((Part)part.getContent());
    }
    return flag;
}
项目:alimama    文件:POP3ReceiveMailTest.java   
/**
 * 获得邮件文本内容
 * @param part 邮件体
 * @param content 存储邮件文本内容的字符串
 * @throws MessagingException
 * @throws IOException
 */
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
    //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;    
    if (part.isMimeType("text/*") && !isContainTextAttach) {
        content.append(part.getContent().toString());
    } else if (part.isMimeType("message/rfc822")) { 
        getMailTextContent((Part)part.getContent(),content);
    } else if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            getMailTextContent(bodyPart,content);
        }
    }
}
项目:alimama    文件:POP3ReceiveMailTest.java   
/**
 * 保存附件
 * @param part 邮件中多个组合体中的其中一个组合体
 * @param destDir  附件保存目录
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
        FileNotFoundException, IOException {
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
        //复杂体邮件包含多个邮件体
        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {
            //获得复杂体邮件中其中一个邮件体
            BodyPart bodyPart = multipart.getBodyPart(i);
            //某一个邮件体也有可能是由多个邮件体组成的复杂体
            String disp = bodyPart.getDisposition();
            if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart,destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(),destDir);
    }
}
项目:job    文件:Job51ResumeParser.java   
private String parseHtml(BodyPart body) throws Exception {
  //System.err.println(body.getContentType());
  if(body.getContentType().startsWith("text/html")) {
    Object content = body.getContent();
    return content == null ? null : content.toString();
  } else if(body.getContentType().startsWith("multipart")) {
    Multipart subpart = (Multipart) body.getContent();
    for(int j = 0; j < subpart.getCount(); j++) {
      BodyPart subbody = subpart.getBodyPart(j);
      String html = parseHtml(subbody);
      if(html != null) {
        return html;
      }
    }
  }
  return null;
}
项目:Camel    文件:MailBinding.java   
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (contentType != null) {
        LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part);

        // always store content in a byte array data store to avoid various content type and charset issues
        String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody());
        // use empty data if the body was null for some reason (otherwise there is a NPE)
        data = data != null ? data : "";

        DataSource ds = new ByteArrayDataSource(data, contentType);
        part.setDataHandler(new DataHandler(ds));

        // set the content type header afterwards
        part.setHeader("Content-Type", contentType);
    }

    return contentType;
}
项目:codenvy    文件:MailReceiverUtils.java   
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart)
    throws MessagingException, IOException {
  StringBuilder result = new StringBuilder();
  int count = mimeMultipart.getCount();
  for (int i = 0; i < count; i++) {
    BodyPart bodyPart = mimeMultipart.getBodyPart(i);
    if (bodyPart.isMimeType("text/plain")) {
      result.append("\n").append(bodyPart.getContent());
    } else if (bodyPart.isMimeType("text/html")) {
      result.append("\n").append((String) bodyPart.getContent());
    } else if (bodyPart.getContent() instanceof MimeMultipart) {
      result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
    }
  }
  return result.toString();
}
项目:play    文件:MailHelper.java   
/**
 * �����Ĵ������ϴ�
 */
private void saveFile(Message message, BodyPart bp) throws Exception {
    String fileName = bp.getFileName();
    if ((fileName != null)) {
        new File(dir).mkdirs(); // �½�Ŀ¼
        fileName = MimeUtility.decodeText(fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String filePath = dir + "/" + UUID.randomUUID() + suffix;
        message.attachMap.put(fileName, filePath);

        File file = new File(filePath);
        BufferedInputStream bis = new BufferedInputStream(bp.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        int i;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.close();
        bis.close();
    }
}
项目:sip-servlets    文件:CallStateHandler.java   
public static String getBodyPart(Multipart multipart, String contentType) throws MessagingException, IOException {
    String body = null;

    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bp = multipart.getBodyPart(i);
        if (contentType.equalsIgnoreCase(bp.getContentType())) {
            BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) bp.getContent()));
            StringBuilder strOut = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                strOut.append(line).append("\r\n");
            }
            body = strOut.toString();
            reader.close();
            break;
        }

    }
    return body;
}
项目:sip-servlets    文件:Test.java   
public static String getBodyPart(Multipart multipart, String contentType) throws MessagingException, IOException {
    String body = null;

    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bp = multipart.getBodyPart(i);
        if (contentType.equalsIgnoreCase(bp.getContentType())) {
            BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) bp.getContent()));
            StringBuilder strOut = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                strOut.append(line).append("\r\n");
            }
            body = strOut.toString();
            reader.close();
            break;
        }

    }
    return body;
}
项目:teammates    文件:EmailAccount.java   
/**
 * Returns the text from multipart/alternative, the type of text returned follows the preference of the sending agent.
 */
private static String getTextFromMultiPartAlternative(Multipart multipart) throws IOException, MessagingException {
    // search in reverse order as a multipart/alternative should have their most preferred format last
    for (int i = multipart.getCount() - 1; i >= 0; i--) {
        BodyPart bodyPart = multipart.getBodyPart(i);

        if (bodyPart.isMimeType("text/html")) {
            return (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("text/plain")) {
            // Since we are looking in reverse order, if we did not encounter a text/html first we can return the plain
            // text because that is the best preferred format that we understand. If a text/html comes along later it
            // means the agent sending the email did not set the html text as preferable or did not set their preferred
            // order correctly, and in that case we do not handle that.
            return (String) bodyPart.getContent();
        } else if (bodyPart.isMimeType("multipart/*") || bodyPart.isMimeType("message/rfc822")) {
            String text = getTextFromPart(bodyPart);
            if (text != null) {
                return text;
            }
        }
    }
    // we do not know how to handle the text in the multipart or there is no text
    return null;
}
项目:Prospero    文件:IrisMessage.java   
private String getBodyText(BodyPart bodyPart) {
Object content;
String disposition;
String bodyText = null;

try {
    content = bodyPart.getContent();
    disposition = bodyPart.getDisposition();
    if (content instanceof String
        && disposition.toLowerCase().contains(
            CONTENT_DISPOSITION_INLINE)) {
    return (String) bodyText;
    }
} catch (Exception e) {
    logger.error(e);
    return "";
}

return bodyText;
   }
项目:greenmail    文件:LargeMessageTest.java   
/**
 * Retrieve message from retriever and check the attachment and text content
 *
 * @param server Server to read from
 * @param to     Account to retrieve
 */
private void retrieveAndCheck(AbstractServer server, String to) throws MessagingException, IOException {
    try (Retriever retriever = new Retriever(server)) {
        Message[] messages = retriever.getMessages(to);
        assertEquals(1, messages.length);
        Message message = messages[0];
        assertTrue(message.getContentType().startsWith("multipart/mixed"));
        MimeMultipart body = (MimeMultipart) message.getContent();
        assertTrue(body.getContentType().startsWith("multipart/mixed"));
        assertEquals(2, body.getCount());

        // Message text
        final BodyPart textPart = body.getBodyPart(0);
        String text = (String) textPart.getContent();
        assertEquals(createLargeString(), text);

        final BodyPart attachment = body.getBodyPart(1);
        assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file"));
        InputStream attachmentStream = (InputStream) attachment.getContent();
        byte[] bytes = IOUtils.toByteArray(attachmentStream);
        assertArrayEquals(createLargeByteArray(), bytes);
    }
}
项目:alfresco-greenmail    文件:GreenMailUtil.java   
public static boolean hasNonTextAttachments(Part m) {
    try {
        Object content = m.getContent();
        if (content instanceof MimeMultipart) {
            MimeMultipart mm = (MimeMultipart) content;
            for (int i=0;i<mm.getCount();i++) {
                BodyPart p = mm.getBodyPart(i);
                if (hasNonTextAttachments(p)) {
                    return true;
                }
            }
            return false;
        } else {
            return !m.getContentType().trim().toLowerCase().startsWith("text");
        }
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
项目:ats-framework    文件:MimePackage.java   
private String addBodyPartTrace(
                                 BodyPart bodyPart,
                                 String level ) throws MessagingException {

    final String level1 = level;
    final String level2 = "\t" + level1;

    StringBuilder msg = new StringBuilder();

    final String prefix = getPrefixTrace(level1, "BODY PART START: ");
    final String contentType = normalizeNewLinesTrace(prefix, bodyPart.getContentType()) + "\n";
    msg.append(level1 + "BODY PART START: " + contentType);
    msg.append(addHeadersTrace(bodyPart.getAllHeaders(), level2));
    msg.append(level1 + "BODY PART END: " + contentType);

    return msg.toString();
}
项目:OrigamiSMTP    文件:Message.java   
private void addPlainTextAttachment(BodyPart b)
{
    try {
        System.out.println("Adding plain text attachment");
        String fileName = getFileName(b.getContentType());
        String content = (String)b.getContent();
        Attachment attach = new Attachment(fileName,content.getBytes());
        attachments.add(attach);
    } catch (MessagingException | IOException e) {
        System.err.println("Could not get file name or read file content");
        e.printStackTrace();
    }
}
项目:unitimes    文件:JavaMailWrapper.java   
@Override
protected void addAttachment(String name, DataHandler data) throws MessagingException {
       BodyPart attachment = new MimeBodyPart();
       attachment.setDataHandler(data);
       attachment.setFileName(name);
       attachment.setHeader("Content-ID", "<" + name + ">");
       iBody.addBodyPart(attachment);
}
项目:onestop-endpoints    文件:EmailPartDocumentDestination.java   
public BodyPart getBodyPart() {
    try {
        DataSource dataSource = new DataSource() {
            @Override public String getContentType() { return contentType; }
            @Override public InputStream getInputStream() { return new ByteArrayInputStream(body.toByteArray()); }
            @Override public String getName() { return filenameOrNull; }
            @Override public OutputStream getOutputStream() { throw new RuntimeException("unreachable"); }
        };

        BodyPart filePart = new MimeBodyPart();
        filePart.setDataHandler(new DataHandler(dataSource));
        if (filenameOrNull != null) {
            filePart.setFileName(filenameOrNull);
            filePart.setDisposition(Part.ATTACHMENT);
        }

        return filePart;
    }
    catch (MessagingException e) { throw new RuntimeException(e); }
}
项目:xframium-java    文件:DefaultReceiveEmailProvider.java   
private String getTextFromMimeMultipart( MimeMultipart mimeMultipart ) throws IOException, MessagingException
{

    int count = mimeMultipart.getCount();
    if ( count == 0 )
        throw new MessagingException( "Multipart with no body parts not supported." );

    boolean multipartAlt = new ContentType( mimeMultipart.getContentType() ).match( "multipart/alternative" );
    if ( multipartAlt )
        return getTextFromBodyPart( mimeMultipart.getBodyPart( count - 1 ) );

    String result = "";
    for ( int i = 0; i < count; i++ )
    {
        BodyPart bodyPart = mimeMultipart.getBodyPart( i );
        result += getTextFromBodyPart( bodyPart );
    }
    return result;
}
项目:scada    文件:MailUtils.java   
/**
 * ����ʼ��ı�����
 * @param part �ʼ���
 * @param content �洢�ʼ��ı����ݵ��ַ���
 */ 
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { 
    //������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж� 
    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;  
    if (part.isMimeType("text/*") && !isContainTextAttach) { 
        content.append(part.getContent().toString()); 
    } else if (part.isMimeType("message/rfc822")) {  
        getMailTextContent((Part)part.getContent(),content); 
    } else if (part.isMimeType("multipart/*")) { 
        Multipart multipart = (Multipart) part.getContent(); 
        int partCount = multipart.getCount(); 
        for (int i = 0; i < partCount; i++) { 
            BodyPart bodyPart = multipart.getBodyPart(i); 
            getMailTextContent(bodyPart,content); 
        } 
    } 
}
项目:azkaban    文件:EmailMessage.java   
public EmailMessage addAttachment(String attachmentName, File file)
    throws MessagingException {

  _totalAttachmentSizeSoFar += file.length();

  if (_totalAttachmentSizeSoFar > _totalAttachmentMaxSizeInByte) {
    throw new MessageAttachmentExceededMaximumSizeException(
        "Adding attachment '" + attachmentName
            + "' will exceed the allowed maximum size of "
            + _totalAttachmentMaxSizeInByte);
  }

  BodyPart attachmentPart = new MimeBodyPart();
  DataSource fileDataSource = new FileDataSource(file);
  attachmentPart.setDataHandler(new DataHandler(fileDataSource));
  attachmentPart.setFileName(attachmentName);
  _attachments.add(attachmentPart);
  return this;
}
项目:azkaban    文件:EmailMessage.java   
public void sendEmail() throws MessagingException {
  checkSettings();
  Properties props = new Properties();
  if (_usesAuth) {
    props.put("mail." + protocol + ".auth", "true");
    props.put("mail.user", _mailUser);
    props.put("mail.password", _mailPassword);
  } else {
    props.put("mail." + protocol + ".auth", "false");
  }
  props.put("mail." + protocol + ".host", _mailHost);
  props.put("mail." + protocol + ".timeout", _mailTimeout);
  props.put("mail." + protocol + ".connectiontimeout", _connectionTimeout);
  props.put("mail.smtp.starttls.enable", _tls);
  props.put("mail.smtp.ssl.trust", _mailHost);

  Session session = Session.getInstance(props, null);
  Message message = new MimeMessage(session);
  InternetAddress from = new InternetAddress(_fromAddress, false);
  message.setFrom(from);
  for (String toAddr : _toAddress)
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(
        toAddr, false));
  message.setSubject(_subject);
  message.setSentDate(new Date());

  if (_attachments.size() > 0) {
    MimeMultipart multipart =
        this._enableAttachementEmbedment ? new MimeMultipart("related")
            : new MimeMultipart();

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(_body.toString(), _mimeType);
    multipart.addBodyPart(messageBodyPart);

    // Add attachments
    for (BodyPart part : _attachments) {
      multipart.addBodyPart(part);
    }

    message.setContent(multipart);
  } else {
    message.setContent(_body.toString(), _mimeType);
  }

  // Transport transport = session.getTransport();

  SMTPTransport t = (SMTPTransport) session.getTransport(protocol);

  try {
    connectToSMTPServer(t);
  } catch (MessagingException ste) {
    if (ste.getCause() instanceof SocketTimeoutException) {
      try {
        // retry on SocketTimeoutException
        connectToSMTPServer(t);
        logger.info("Email retry on SocketTimeoutException succeeded");
      } catch (MessagingException me) {
        logger.error("Email retry on SocketTimeoutException failed", me);
        throw me;
      }
    } else {
      logger.error("Encountered issue while connecting to email server", ste);
      throw ste;
    }
  }
  t.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
  t.close();
}