There was a problem with this two days about sending mail using Java Mail.
In detail, I use Java mail to send an exception report message with an attachment that contains an exception log, and a message body about the device information. If the log suffix is the name, then it appears normal in my QQ mailbox. But assuming the suffix name of the attachment is changed to TXT, The contents of the attachment are displayed directly in the message body. And the message body I originally set up is not there.
My code is written like this:
Add to Attachment:
public void AddAttachment (string filePath, String fileName) throws Exception { BodyPart messagebodypart = new Mimebody Part (); ((MimeBodyPart) messagebodypart). Attachfile (FilePath); Multipart.addbodypart (Messagebodypart); }
To send a message:
public Boolean send () throws Messagingexception {if (!user.equals ("") &&!pass.equals ("") &&!to. Equals ("") &&!from.equals ("")) {Session session = Session.getdefaultinstance (props, this); LOG.D ("Sendutil", Host + "..." + Port + "..." + user + "..." + Pass); MimeMessage msg = new MimeMessage (session); Msg.setfrom (New InternetAddress (from)); InternetAddress Addressto = new internetaddress (to); Msg.setrecipient (MimeMessage.RecipientType.TO, Addressto); Msg.setsubject (subject); Msg.setsentdate (New Date ()); Setup message body bodypart Messagebodypart = new MimeBodyPart (); Messagebodypart.settext (body); Multipart.addbodypart (Messagebodypart); Put parts in Message msg.setcontent (multipart); Send email Transport.send (msg); return true; } else { return false; } }
Later I tried to send the email to NetEase. The discovery becomes the text is blank. But the attachment is one more. The second attachment is what I set up in the body of the message.
All kinds of Baidu, Google, StackOverflow did not find the answer. Later I think, in such a way e-mail, is not QQ mailbox will be the first TXT attachment as the body display. So changed the code to set the body of the message such as the following, the body is set to multipart the first one:
Setup message body bodypart Messagebodypart = new MimeBodyPart (); Messagebodypart.settext (body); Multipart.addbodypart (Messagebodypart, 0);
Send the message again test, the results in QQ and NetEase mail are displayed normal.
Resolves an issue where the TXT attachment sent by Java Mail is displayed directly in the body