Search code examples
javajakarta-mail

JavaMail attachment and body issue


I am using below code to attach a pdf file to mail (JAVAMAIL). this postion works perfectly and adds attachment to my mail but this mail does not have any body.

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);
        DataSource source = new FileDataSource(pdf);
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(pdf.getName().toString());
        multipart.addBodyPart(messageBodyPart);
        msg.setContent(multipart);

when i add below lines to my code it removes attachment and send me mail containing the text only.

msg.setText(body);

please help me to add both attachment and test body to my mail.


Solution

  • The problem is that if you want to send a message with attachments, then you need to have a part for your message, and a part for your attachment.

    By calling setText in the message, you are throwing away the multipart you set earlier.

    Your message needs to have an hierarchy that looks like this (more nesting is necessary if you want to have a plain text and html message):

    MimeMessage
    +- MimeMultiPart
       +- MimeBodyPart (message)
       +- MimeBodyPart (attachment)
    

    For example

    MimeMessage message = new MimeMessage(session);
    MimeMultiPart multiPart = new MimeMultiPart();
    
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(body);
    multiPart.addBodyPart(messageBodyPart);
    
    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setDataHandler(new DataHandler(source));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName(pdf.getName().toString());
    multipart.addBodyPart(attachment);
    
    message.setContent(multiPart);