Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从电子邮件中获取内联图像?_Java_Jakarta Mail_Email Attachments_Inline Images - Fatal编程技术网

Java 如何从电子邮件中获取内联图像?

Java 如何从电子邮件中获取内联图像?,java,jakarta-mail,email-attachments,inline-images,Java,Jakarta Mail,Email Attachments,Inline Images,我正在使用下一个代码使用javamail API从我的邮箱帐户下载附件和正文,它工作得很好。但是,当电子邮件上有内嵌或嵌入的图像时,这些图像不会以文本或附件文件的形式下载。我是Java新手,一直在网上阅读,但没有找到一个易于理解的实现解决方案。有什么工作或代码来完成吗 这是我正在使用的代码: public void processMessageBody(Message message) { try { Object content = message.getContent

我正在使用下一个代码使用javamail API从我的邮箱帐户下载附件和正文,它工作得很好。但是,当电子邮件上有内嵌或嵌入的图像时,这些图像不会以文本或附件文件的形式下载。我是Java新手,一直在网上阅读,但没有找到一个易于理解的实现解决方案。有什么工作或代码来完成吗

这是我正在使用的代码:

public void processMessageBody(Message message) {
    try {
        Object content = message.getContent();
        // check for string
        // then check for multipart
        if (content instanceof String) {
            System.out.println(content);
        } else if (content instanceof Multipart) {
            Multipart multiPart = (Multipart) content;
            procesMultiPart(multiPart);
        } else if (content instanceof InputStream) {
            InputStream inStream = (InputStream) content;
            int ch;
            while ((ch = inStream.read()) != -1) {
                System.out.write(ch);
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

public void procesMultiPart(Multipart content) {

    try {

        for (int i = 0; i < content.getCount(); i++) {
            BodyPart bodyPart = content.getBodyPart(i);
            Object o;

            o = bodyPart.getContent();
            if (o instanceof String) {
                System.out.println("Text = " + o);
            } else if (null != bodyPart.getDisposition()
                    && bodyPart.getDisposition().equalsIgnoreCase(
                            Part.ATTACHMENT)) {
                String fileName = bodyPart.getFileName();
                System.out.println("fileName = " + fileName);
                InputStream inStream = bodyPart.getInputStream();
                FileOutputStream outStream = new FileOutputStream(new File(
                        downloadDirectory + fileName));
                byte[] tempBuffer = new byte[4096];// 4 KB
                int numRead;
                while ((numRead = inStream.read(tempBuffer)) != -1) {
                    outStream.write(tempBuffer);
                }
                inStream.close();
                outStream.close();
            }
            // else?

        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}
public void processMessageBody(消息消息){
试一试{
对象内容=message.getContent();
//检查字符串
//然后检查多部分
if(字符串的内容实例){
系统输出打印项次(内容);
}else if(多部分的内容实例){
多部分多部分=(多部分)内容;
过程多部分(多部分);
}else if(InputStream的内容实例){
InputStream inStream=(InputStream)内容;
int-ch;
而((ch=inStream.read())!=-1){
系统输出写入(ch);
}
}
}捕获(IOE异常){
e、 printStackTrace();
}捕获(消息异常e){
e、 printStackTrace();
}
}
public void procesMultiPart(多部分内容){
试一试{
for(int i=0;i
我已尝试添加下一个if语句,以在其为内联图像时显示消息,但没有成功:

 public void procesMultiPart(Multipart content) {

        try {

            for (int i = 0; i < content.getCount(); i++) {
                BodyPart bodyPart = content.getBodyPart(i);
                Object o;

                o = bodyPart.getContent();
// NOT WORKING
                if (o instanceof Image) {
                   System.out.println("procesMultiPart has Inline Images");
                } 
// 
else if (o instanceof String) {
                    System.out.println("Text = " + o);
                } else if (null != bodyPart.getDisposition()
                        && bodyPart.getDisposition().equalsIgnoreCase(
                                Part.ATTACHMENT)) {
                    String fileName = bodyPart.getFileName();
                    System.out.println("fileName = " + fileName);
                    InputStream inStream = bodyPart.getInputStream();
                    FileOutputStream outStream = new FileOutputStream(new File(
                            downloadDirectory + fileName));
                    byte[] tempBuffer = new byte[4096];// 4 KB
                    int numRead;
                    while ((numRead = inStream.read(tempBuffer)) != -1) {
                        outStream.write(tempBuffer);
                    }
                    inStream.close();
                    outStream.close();
                }
                // else?

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
public void procesMultiPart(多部分内容){
试一试{
for(int i=0;i
以下代码应该适合您

private String getAttachments(Message message, HttpServletRequest request) throws MessagingException, IOException {
String contentType = message.getContentType();
String attachFiles="";
if (contentType.contains("multipart")) {
    // content may contain attachments
    Multipart multiPart = (Multipart) message.getContent();
    int numberOfParts = multiPart.getCount();
    for (int partCount = 0; partCount < numberOfParts; partCount++) {
        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
        String disposition =part.getDisposition();
        String file=part.getFileName();
        //External attachments
        if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            // this part is attachment
            String fileName = new Date().getTime()+ "_"+ part.getFileName().replaceAll("[^a-zA-Z0-9\\._]+", "_"); //To make attachment name uniq we are adding current datatime before name.
            attachFiles += fileName + ","; //concrete all attachment's name with comma separated.                  
            part.saveFile(new File(request
                    .getSession()
                    .getServletContext()
                    .getRealPath(
                            "/WEB-INF/attechments/"
                                    + fileName)));   //To save the attachment file at specific location.
    //                    LOG.info("\n\t Path :- " +request.getSession().getServletContext().getRealPath("/WEB-INF/attechments/" + fileName));
        }
        //Inline Attachments
        else if (disposition != null && Part.INLINE.equalsIgnoreCase(disposition)) {
            // this part is attachment
            String fileName = new Date().getTime()+ "_"+ part.getFileName().replaceAll("[^a-zA-Z0-9\\._]+", "_"); //To make attachment name uniq we are adding current datatime before name.
          //  attachFiles += fileName + ","; //concrete all attachment's name with comma separated.                  
            part.saveFile(new File(request
                    .getSession()
                    .getServletContext()
                    .getRealPath(
                            "/WEB-INF/attechments/"
                                    + fileName)));   //To save the attachment file at specific location.
//                    LOG.info("\n\t Path :- " +request.getSession().getServletContext().getRealPath("/WEB-INF/attechments/" + fileName));
        }
        //Inline icons and smileys
        else if(file != null && disposition==null)
        {
            String fileName = new Date().getTime()+ "_"+ part.getFileName().replaceAll("[^a-zA-Z0-9\\._]+", "_");
        //  attachFiles += fileName + ","; //concrete all attachment's name with comma separated.
             part.saveFile(new File(request
                    .getSession()
                    .getServletContext()
                    .getRealPath(
                            "/WEB-INF/attechments/"
                                    + fileName))); 

        }
    }
 }
 if (attachFiles.length() > 1) {
     attachFiles = attachFiles.substring(0, attachFiles.length() - 1);
 }
return attachFiles;
}
私有字符串getAttachments(消息消息,HttpServletRequest请求)抛出MessaginException,IOException{
字符串contentType=message.getContentType();
字符串附件=”;
if(contentType.contains(“多部分”)){
//内容可能包含附件
Multipart Multipart=(Multipart)message.getContent();
int numberOfParts=multiPart.getCount();
对于(int partCount=0;partCountpublic static List<String> getAttachmentFileName(MimeMultipart mimeMultipart) throws Exception{
        List<String> attachFileNameList = new ArrayList<String>();
        int count = mimeMultipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            if("ATTACHMENT".equalsIgnoreCase(bodyPart.getDisposition())){
                attachFileNameList.add(bodyPart.getFileName());
            }
        }
        return attachFileNameList;
    }
private static void fillBodyAndAttachments(Message message) throws Exception {
        String body = "";
        List<FileData> attachments = new LinkedList<>();
        String contentType = message.getContentType();

        if (contentType.contains("text/plain") || contentType.contains("text/html")) {
            Object content = message.getContent();
            if (content != null) {
                body = content.toString();
            }
            System.out.println(body);
            return;
        }

        if (contentType.contains("multipart")) {
        Multipart multiPart = (Multipart) message.getContent();
        int numberOfParts = multiPart.getCount();
        for (int partCount = 0; partCount < numberOfParts; partCount++) {
            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
            String disposition = part.getDisposition();

            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                addAttachment(attachments, part);
            } else if (Part.INLINE.equalsIgnoreCase(disposition)) {
                Object content = part.getContent();
                if (content instanceof InputStream) {
                    var inputStream = (InputStream) content;
                    byte[] byteArray = IOUtils.toByteArray(inputStream);
                    addInlineAttachment(attachments, byteArray, part.getFileName());
                }
            } else {
                Object content = part.getContent();
                if (content instanceof String) {
                    body = (String) content;
                } else if (content instanceof InputStream) {
                    body = new String(IOUtils.toByteArray((InputStream) content));
                } else if (content instanceof IMAPNestedMessage) {
                    IMAPNestedMessage imapNestedMessage = (IMAPNestedMessage) content;
                    body = new String(IOUtils.toByteArray(imapNestedMessage.getInputStream()));
                } else {
                    MimeMultipart mimeMultipart = (MimeMultipart) part.getContent();
                    body = new String(IOUtils.toByteArray(mimeMultipart.getBodyPart(0).getInputStream()));
                }
            }
        }
    }
        System.out.println(body);
        System.out.println(attacments.size());
    }
 private static void addAttachment(List<FileData> attachments, MimeBodyPart part) throws Exception {
    String fileName = part.getFileName();
    FileData fileData = new FileData()
            .setName(fileName)
            .setData(part.getInputStream().readAllBytes())
            .setType(getMimeType(fileName));
    attachments.add(fileData);
}

private static void addInlineAttachment(List<FileData> attachments, byte[] data, String fileName) throws Exception {
    FileData fileData = new FileData()
            .setName(fileName)
            .setData(data)
            .setType(getMimeType(fileName));
    attachments.add(fileData);
}

private static String getMimeType(String fileName) throws Exception {
    Path path = new File(fileName).toPath();
    return Files.probeContentType(path);
}
@Data
@Accessors(chain = true)
public class FileData {
    byte[] data;
    String name;
    String type;
}