title: How to modify existing Java mail MimeMessage body parts?
body: <p>I am trying to modify existing MimeMessage body part. I would like to filter certain links. Does any of you know why even though body part content seams to be changed message is sent with old content? Is there some caching going on? Any idea how to solve this?</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public void resend(InputStream data) throws Exception {
      Session mailSession = createMailSession();
      //mailSession.setDebug(true);
  
      Transport transport = mailSession.getTransport();
      MimeMessage message = new MimeMessage(mailSession, data);
  
      Object content = message.getContent();
      if (content.getClass().isAssignableFrom(MimeMultipart.class)) {
          MimeMultipart mimeMultipart = (MimeMultipart) content;
  
          for (int i = 0; i &lt; mimeMultipart.getCount(); i++) {
  
              BodyPart bodyPart = mimeMultipart.getBodyPart(i);
              if (bodyPart.getContentType().startsWith("text/plain")) {
                  String cnt = updateContent((String) bodyPart.getContent());
                  System.out.println("ContentType = " + bodyPart.getContentType());
                  System.out.println("Content = " + cnt);
  
                  bodyPart.setContent(cnt, bodyPart.getContentType());
              } else if (bodyPart.getContentType().startsWith("text/html")) {
                  String cnt = updateContent((String) bodyPart.getContent());
                  System.out.println("ContentType = " + bodyPart.getContentType());
                  System.out.println("Content = " + cnt);
  
                  bodyPart.setContent(cnt, bodyPart.getContentType());
              }
          }
      } else {
          String cnt = updateContent((String) message.getContent());
          System.out.println("ContentType = " + message.getContentType());
          System.out.println("Content = " + cnt);
  
          message.setContent(cnt, message.getContentType());
      }
  
      transport.connect();
      transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
      transport.close();
  }
  
  private String updateContent(String cnt) {
      return cnt.replace("www.xyz.pl", "www.new-xyz.pl");
  }
  </code></pre>
  
  <p>Input stream "data" contains raw message.</p>
  
  <p>Any ideas?</p>
  
  <p>Thanks in advance....</p>