roger_that
roger_that

Reputation: 9791

Specifying the filename while creating a File Object it from byte array (without creating a physical file)

I was stuck to a problem exactly same as this and with the solution posted i was able to solve my issue. But now the problem is, when the attachment is received, there is no name for it. In my method, i have asked for receiver's email id, subject , content, filename and byte[] for the File. There is no problem in format of the file i am passing but problem is with the name. The recipient gets "noname" as file name. How do we specify the filename of our choice. The filename which i am passing as parameter doesnt gets reflected. Please suggest.

The code which i am using is

File file = new File("D:/my docs/Jetty.pdf");
int len1 = (int)(file.length());
FileInputStream fis1 = null;
try {
    fis1 = new FileInputStream(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
byte buf1[] = new byte[len1];
try {
    fis1.read(buf1);
    EmailServiceClient.sendEmailWithAttachment("[email protected]", "[email protected]", "Hi", "PFA", "Jetty.pdf", buf1);

    System.out.println("SENT");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

My email service Implementation for this goes here

public void sendEmailWithAttachment(String emailIdTo, String emailIdFrom, String subject, String content,
    final String fileName, byte[] file) {
MimeMessage message = mailSender.createMimeMessage();
try {
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(emailIdTo);
    helper.setFrom(emailIdFrom);
    helper.setSubject(subject);
    helper.setText(content, true);
    helper.addInline("attachment", new ByteArrayResource(file) {
        @Override
        public String getFilename() {
            return fileName;
        }
    });
    mailSender.send(message);
} catch (MessagingException e) {
    throw new MailParseException(e);
}}

Please someone help in figuring this out

Upvotes: 1

Views: 1023

Answers (1)

toomasr
toomasr

Reputation: 4781

From the Spring Documentation I can say that the inlined elements don't have special names besides the contentId. Maybe you want to add an attachment instead using the addAttachment method? Then you can have a name for your file.

http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/mail/javamail/MimeMessageHelper.html

Upvotes: 1

Related Questions