0
votes
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
message.setFileName("abc.xls");
message.setText("Fill the content:");

Above is the main part of code which I am using. While I use the above code, i don't see main body content "Fill the content" in the sent mail. There are other posts and comments which have piece of code which works that's this problem cab be resolved by using MimeMultipart & MimeBodyPart class. But no where it's explained the reason of why the above code is not working.

I am also aware that using setFileName is not enough to add the content present inside the file, it's just used to add the attachment without content.

Note: I am using javax.mail-1.5.0.jar

Can you please explain the reason of the above code not working?

Thanks in advance.

1
Do you just set a file name or do you actually add some file there somewhere? - RealSkeptic
I just did setFileName & that file is present in that location. - Rohit Kumar

1 Answers

1
votes

A mail that contains a text message and one or more attachments must be a MultiPart message, because that's the way such a mail is constructed so the receiving mail client understands it.

In your simple example, you are not constructing a mail that has an excel file abc.xls as attachment; instead, you create a text mail and tell the client that the body of this mail should be named abc.xls. Most likely, the receiving mail client will offer a text file with the content Fill the content:, inappropriately named abc.xls, as an attachment of an otherwise empty mail; opening the supposed Excel file will probably cause Excel to import this text file.

TL;DR: Use MimeMultiPart to create mails with attachments.