Search code examples
javaemailjakarta-mailmultipartmailer

Javamail : Not able to send an email with message body, text/html and attachment.


I am able to get all the message , html and attachment in the mail but the message text is received as a text file.

I want the message to be displayed in the mail.Any help would be appreciated.

     final String subject = "Automation Execution Report"; 

Message text that has to be sent

    StringBuilder msg = new StringBuilder();
    msg.append("Hi All"+"\n");
    msg.append("We have executed the Automation Suite in current 
    build."+"\n");
    msg.append("Please find the automation report in the attachment");

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        //below code only requires if your want cc email address
        message.setSubject(subject);
        File dir = new File(System.getProperty("user.dir")+ 
        File.separator+"test_reports");
        File[] files = dir.listFiles();

        File lastModifiedFile = files[0];
        for (int i = 1; i < files.length; i++) {
           if (lastModifiedFile.lastModified() < files[i].lastModified()) {
               lastModifiedFile = files[i];
           }
        }
        String attach = lastModifiedFile.toString();

Multiparts created

        Multipart parent = new MimeMultipart("alternative");
        Multipart child=new MimeMultipart("mixed");

        message.setSubject(subject);

Customized report in html format being printed on the mail

        MimeBodyPart htmlpart = new MimeBodyPart();
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File("D:\\SVN CODE\\test- 
         output\\customized-emailable-report.html")), writer);
        htmlpart.setContent(writer.toString(), "text/html");

        child.addBodyPart(htmlpart);

Message text which has to be printed on the mail

        MimeBodyPart txtpart=new MimeBodyPart();
        txtpart.setContent(msg.toString(), "text/plain");
        child.addBodyPart(txtpart);
        //Adding the child multipart to parent multtipart     
        MimeBodyPart sub=new MimeBodyPart();
        sub.setContent(child);
        parent.addBodyPart(sub);
        //Attachment part   
        BodyPart attachPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attach);
        attachPart.setDataHandler(new DataHandler(source));
        attachPart.setFileName("Test Automation report.html");
        parent.addBodyPart(attachPart);

Setting the content to the message

         message.setContent(parent);

        System.out.println("Sending");

        Transport transport = session.getTransport("smtp");
        transport.connect(host,25,from, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        System.out.println("Done");

      } 

  [1]: https://i.sstatic.net/InHyZ.png
Please advise as to how the message text can be printed on the mail

Solution

  • You need to use MimeMultipart and add MimeBodyPart elements to it.

    MimeMultipart multipart = new MimeMultipart();
    
    String htmlContent = "<p>Hello World!</p>"
    // add HTML content here
    final MimeBodyPart  messageBodyPart = new MimeBodyPart();
    // HTML Content
    messageBodyPart.setContent(htmlContent, "text/html;charset=UTF-8");
    
    // add it
    multipart.addBodyPart(messageBodyPart);
    
    // don't forget to add the content to your message.
    message.setContent(multipart);
    

    With this method, you can add an attachment as another MimeBodyPart :

         String filePath = "/tmp/dummy.txt"
         MimeBodyPart bodyPart = new MimeBodyPart();
         DataSource source = new FileDataSource(filePath);
         bodyPart.setDataHandler(new DataHandler(source));
         bodyPart.setFileName(fileName);
         multipart.addBodyPart(bodyPart);
    

    EDIT Did not see that you were already using a multipart. Your problem here only lies with the content type you are setting. You must use "text/html" instead of "text/plain"