Does javamail load memory before sending?

I need to create an email with an attachment that is compiled on the fly. In my first draft of this, I built the attachment as a String. But on walkthru code, others noted that the string can be very large. Usually it is several thousand bytes, but sometimes it can be megabytes. Therefore, they said that I should write it in turn to a temporary file, and then attach the file to the letter. Otherwise, I may run out of empty space.

I am wondering if this really helps. If JavaMail reads the entire file into memory before sending, it does not matter. And, of course, creating a temporary file causes other troubles, such as finding the right directory to make sure I have permissions, etc. But if, instead, Javamail reads the file in some small chunks, then it would avoid the memory problem.

The bottom line is: as I understand it, Javamail sends synchronously. Therefore, if I create a file, send it, and then delete the file, there should be no problem deleting the file before actually sending it, right?

+3
source share
2 answers

If you are using a DataHandler implementation, yes, you can pass it. We do it all the time

            MimeBodyPart mbp2 = new MimeBodyPart();
            //  attach the file to the message
            mbp2.setDataHandler(new DataHandler(fids[i]));
            mbp2.setFileName(fids[i].getName());

fid [i] ​​ DataSource

public abstract interface javax.activation.DataSource {

  // Method descriptor #4 ()Ljava/io/InputStream;
  public abstract java.io.InputStream getInputStream() throws java.io.IOException;

  // Method descriptor #8 ()Ljava/io/OutputStream;
  public abstract java.io.OutputStream getOutputStream() throws java.io.IOException;

  // Method descriptor #10 ()Ljava/lang/String;
  public abstract java.lang.String getContentType();

  // Method descriptor #10 ()Ljava/lang/String;
  public abstract java.lang.String getName();
}
+3

, , MJB, , , . :

File file = new File("huge-message.txt");
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(...);
msg.setRecipient(...);
msg.setSubject(...);
msg.setDataHandler(new DataHandler(new FileDataSource(file)));
+2

All Articles