简体   繁体   中英

JavaMail delete Content-Length header after send

One of my client use specific mail server to receive any data. To send file, I need use headers like this:

...
MIME-Version: 1.0
Content-Type: application/octet-stream; name=file.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=file.zip
Content-Length: 9245

--- base64 file content ---
...

I use this code to create a message, using JavaMail(v1.4.7)

final SMTPMessage message = new SMTPMessage(session); // I use SMTPMessage for add extensions 
message.setDisposition("attachment; filename=" + fileName);
message.setContent(content, "application/octet-stream; name=" + fileName);
message.setHeader("Content-Length", String.valueOf(content.length));
message.saveChanges();
...
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
message.setMailExtension("SIZE=" + baos.size());

final SMTPTransport tr = (SMTPTransport) session.getTransport("smtp");
tr.connect(user, password); // I need to use SMTP and POP3 authorization
final Address[] a = new Address[adrses.size()];
tr.sendMessage(message, adrses.toArray(a));
tr.close();

When I send mail with props.setProperty("mail.debug", "true"); , in log I don't see Content-Length header. Without Content-Length, server don't receive message.

Please help! How to add Content-Length correctly

The Content-Length header is never supposed to be included in messages in transit. The SMTP protocol defines the length of the message, independent of the header. No SMTP server should ever require the header in messages it receives. The Content-Length header is only intended for use in Unix mailboxes where multiple messages are combined in a single file. If you have a server that requires the Content-Length header, it's broken and should be fixed.

If you really, really, really want to send a message with a Content-Length header, you'll need to subclass MimeMessage and override the writeTo method with an ignoreList and remove "Content-Length" from the ignoreList before calling super.writeTo.

Also, you should really consider upgrading to the current version of JavaMail .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM