简体   繁体   English

如何在java中使用mimemessage class获取email正文和附件

[英]How to get email body text and attachments using mimemessage class in java

In my SMTP server code, I have a MimeMessage instance that I want to use for extracting the incoming mailbody(mail text) and mail attachments.在我的 SMTP 服务器代码中,我有一个 MimeMessage 实例,我想用它来提取传入的邮件正文(邮件文本)和邮件附件。 To do this, I use the below implementation on client and server sides.为此,我在客户端和服务器端使用了以下实现。 However, I am only able to retrieve mail attachments.但是,我只能检索邮件附件。 The code somehow detects CustomerEngineer.ahmet thing two times and none of them contains the mail body which is: "This is a message body".该代码以某种方式两次检测到 CustomerEngineer.ahmet 事物,并且它们都不包含邮件正文:“这是邮件正文”。 I can retrieve the image though.我可以检索图像。

In my java mail client, I created a mail with the following schema:在我的 java 邮件客户端中,我创建了一个具有以下架构的邮件:

try {
        // Create a default MimeMessage object
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject
        message.setSubject("Hi JAXenter");

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("This is a message body");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        DataSource source = new FileDataSource(new File(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\CustomerEngineer.png")));
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("CustomerEngineer.ahmet");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

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

On my server side I use the following logic:在我的服务器端,我使用以下逻辑:

 MimeMessage message = new MimeMessage(session, data);

public void seperateBodyAndAttachments(MimeMessage message) throws MessagingException, IOException {
    String mimeType = message.getContentType();
    Date dt = new Date();

    if (message.isMimeType("text/*")) {
        System.out.println("this containst a text file");
    }  else if (message.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) message.getContent();
        int idx = 0;
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart part = mp.getBodyPart(i);
            String name = part.getDataHandler().getName();
            if (part.isMimeType("text/*")) {
                if (name == null) {
                    name = "text-" + (++idx) + ".txt";
                }
                System.out.println(name);
            } else {
                if (name == null) {
                    name = "attachment-" + (++idx);
                }
                FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\resources\\DevEnvironmentConfigFile\\" + name));
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                part.getDataHandler().writeTo(bos);
                bos.close();
            }
        }
    } else if (message.isMimeType("message/rfc822")) {
        // Not implemented
    } else {
        Object o = message.getContent();
        if (o instanceof String) {
            FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  + "text.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write((String)o);
            bw.close();
        } else if (o instanceof InputStream) {
            FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  +"message.dat"));
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            message.getDataHandler().writeTo(bos);
            bos.close();
        } else {
            FileWriter fw = new FileWriter(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\downloads\\"  +"unknown.txt"));
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write((String)o);
            bw.close();
        }
    }
}

Not quite sure about your email structure.不太确定您的 email 结构。 But be aware that multiparts can be nested - so you'll have to go all the way down in your search for the body.但请注意,多部分可以嵌套 - 因此在搜索正文时您必须一直向下 go 。 And with mutlipart/alternative, there might be more than one body.而使用 mutlipart/alternative,可能会有不止一个实体。

In your case, you could be looking at在您的情况下,您可能正在查看

multipart/mixed
  multipart/alternative
    text/plain
    text/html
attachment

kind of structure.种结构。 So the first multipart really does not include the body.所以第一个多部分真的不包括身体。 Consider this code:考虑这段代码:

public void seperateBodyAndAttachments(MimeMessage mm) throws MessagingException, IOException {
   String mimeType = message.getContentType();
   System.out.println("Message is a " + mimeType);  
   Object content = mm.getContent();
   if(content instanceof String) {
     System.out.println("Body: " + content);
   } else if(content instanceof MimeMultipart) {                
     MimeMultipart multi = (MimeMultipart)content;
     System.out.println("We have a "+ multi.getContentType());              
     for(int i = 0; i < multi.getCount(); ++i) {
        BodyPart bo = multi.getBodyPart(i);
        System.out.println("Content "+i+" is a " + bo.getContentType());
        //Now that body part could again be a MimeMultipart...
        Object bodyContent = bo.getContent();
        //possibly build a recurion here -> the logic is the same as for mm.getContent() above
      }
    } else {
        System.out.println("Some other content: " + content.getClass().getName());
    }
}

In your case, the confusion comes from adding body-part twice:在您的情况下,混淆来自两次添加 body-part :

    // This is the object created
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("This is a message body");

    Multipart multipart = new MimeMultipart();

    // you add a reference to this object into the multipart
    multipart.addBodyPart(messageBodyPart);


    DataSource source = new FileDataSource(new File(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\CustomerEngineer.png")));

    //you CHANGE THE CONTENTS of the object to now contain your attachment
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName("CustomerEngineer.ahmet");

    //and add it a second time.
    multipart.addBodyPart(messageBodyPart);

Maybe try this for sending:也许试试这个发送:

        // Set Subject
        message.setSubject("Hi JAXenter");


        Multipart multipart = new MimeMultipart("mixed");
        //Add Text Part         
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent("This is a message body", "text/plain");
        multipart.addBodyPart(textBodyPart);

        //Add attachment
        DataSource source = new FileDataSource(new File(System.getProperty("user.dir").concat("\\src\\main\\java\\emailrelayserver\\CustomerEngineer.png")));
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("CustomerEngineer.ahmet");
        multipart.addBodyPart(messageBodyPart);

        //Set this as message content
        message.setContent(multipart);



        //This will show you internal structure of your message! D
        message.saveChanges();
        message.writeTo(System.out);

        Transport.send(message);            

In my case I needed to extract a MimeBodyPart from a MimeMessage .在我的例子中,我需要从MimeMessage中提取一个MimeBodyPart It was trickier than I thought but I ended up robbing these 2 methods from BouncyCastle这比我想象的要棘手,但我最终从BouncyCastle中抢走了这两种方法

 /**
 * extract an appropriate body part from the passed in MimeMessage
 */
protected MimeBodyPart makeContentBodyPart(
    MimeMessage message)
    throws SMIMEException
{
    MimeBodyPart content = new MimeBodyPart();
    //
    // add the headers to the body part.
    //
    try
    {
        message.removeHeader("Message-Id");
        message.removeHeader("Mime-Version");

        // JavaMail has a habit of reparsing some content types, if the bodypart is
        // a multipart it might be signed, we rebuild the body part using the raw input stream for the message.
        try
        {
            if (message.getContent() instanceof Multipart)
            {
                content.setContent(message.getRawInputStream(), message.getContentType());
                extractHeaders(content, message);
                return content;
            }
        }
        catch (MessagingException e)
        {
            // fall back to usual method below
        }
        content.setContent(message.getContent(), message.getContentType());
        content.setDataHandler(message.getDataHandler());
        extractHeaders(content, message);
    }
    catch (MessagingException e)
    {
        throw new SMIMEException("exception saving message state.", e);
    }
    catch (IOException e)
    {
        throw new SMIMEException("exception getting message content.", e);
    }

    return content;
}

private void extractHeaders(MimeBodyPart content, MimeMessage message)
    throws MessagingException
{
    Enumeration e = message.getAllHeaders();

    while (e.hasMoreElements())
    {
        Header hdr = (Header)e.nextElement();
        content.addHeader(hdr.getName(), hdr.getValue());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java MimeMessage电子邮件打印标题信息在正文中 - Java MimeMessage email printing header info in body 如何为带有附件的Java MimeMessage对象创建测试数据? - How to create test data for Java MimeMessage objects with attachments? 如何使用 OutputStream 在 Java 中向电子邮件添加附件? - How to add attachments to email in Java using OutputStream? Java - 将原始电子邮件内容文本 RFC 822 转换为 MimeMessage - Java - Convert the Raw Email Content Text RFC 822 to MimeMessage 如何使用Java中的EWS从交换服务器获取文本中的电子邮件正文? - how to get email body in text from exchange server using EWS in java? 如何修改现有的Java邮件MimeMessage正文部分? - How to modify existing Java mail MimeMessage body parts? 如何从MimeMessage Java中的电子邮件中裁剪用户签名 - How to trim off the user signature from Email in MimeMessage java 如何使用 Sketchware 修改 Java 代码以发送多个 email 附件? - How to amend Java code to send multiple email attachments, using Sketchware? 我尝试在MimeMessage的Java方法中发送带有主体内容附件的电子邮件时,主体内容未发送 - Body content is not being sent while I am trying to send an email with attachment with main body content in Java methods of MimeMessage 读取 Email 的文本文件转换为 Javamail MimeMessage - Read text file of Email convert to Javamail MimeMessage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM