Search code examples
javax

How to add Microsoft Word content in Email Body from Java Code


I am trying to put content of Microsoft Word Document in Email body from Java Code but getting following error:

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
    at co.kush.DemoEmail.main(DemoEmail.java:134)
Caused by: javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
    at co.kush.DemoEmail.main(DemoEmail.java:128)
Caused by: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:896)
    at javax.activation.DataHandler.writeTo(DataHandler.java:317)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)

Refer my code :

package co.kush;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.CharacterRun;


/**
* @author Kush 
* 
*/
public class DemoEmail {
 public static void main(String[] args) throws FileNotFoundException, IOException {

        Properties prop = new Properties();
        String Filepath = "Email.Properties";
        FileInputStream propFile = new FileInputStream(Filepath);
        prop.load(propFile);
        String timeStamp = new SimpleDateFormat("M/dd @ HH:mm:ss").format(Calendar.getInstance().getTime());

        // Fetching values from property file
        String sender = prop.getProperty("sender");
        String recevier = prop.getProperty("recevier");
        String password = prop.getProperty("password");
        String proxyHost = prop.getProperty("proxyHost");
        String proxyPort = prop.getProperty("proxyPort");
        String smtpHost = prop.getProperty("smtpHost");
        String smtpPort = prop.getProperty("smtpPort");
        String attachFilePath = prop.getProperty("attachFilePath");
        String mailSubject=prop.getProperty("mailSubject")+"  on " + timeStamp;
        String mailBody = prop.getProperty("mailBody");

        Properties sys_prop = System.getProperties();

        // Setting values for sending Email
        sys_prop.put("mail.smtp.starttls.enable", "true");
        sys_prop.put("mail.transport.protocol", "SMTP");
        sys_prop.put("mail.smtp.host", smtpHost);
        sys_prop.put("mail.smtp.auth", "true");
        sys_prop.put("mail.smtp.port", smtpPort);
        sys_prop.put("mail.smtp.debug", "true");
        sys_prop.put("mail.smtp.socketFactory.port", smtpPort);
        sys_prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        sys_prop.put("mail.smtp.socketFactory.fallback", "false");
        sys_prop.put("proxySet", "true");
        sys_prop.put("proxyPort", proxyPort);
        sys_prop.put("socksProxyHost", proxyHost);
        sys_prop.put("proxyHost", proxyHost);

        Session session = Session.getDefaultInstance(sys_prop, null);

        try {
            //Adding Sender/Receiver address and Subject Line
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(sender));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recevier));
            msg.setSubject(mailSubject);            

            MimeBodyPart messageBodyPart=new MimeBodyPart();
            Multipart multipart = new MimeMultipart();

            //Reading Word Document
              HWPFDocument doc = new HWPFDocument(new FileInputStream("<AbsolutePathWordDoc\\<WordDocFile>.doc"));
                WordExtractor we = new WordExtractor(doc);
                String[] paragraphs = we.getParagraphText();
                   for (String para : paragraphs) {
                    //Putting word document to email Body
                    messageBodyPart.setContent(paragraphs, "application/msword");
                    multipart.addBodyPart(messageBodyPart);
                }


            //Adding attachment and Body content to MIME msg object
            msg.setContent(multipart);

            //Sending the message
            Transport transport = session.getTransport("smtp");
            transport.connect(smtpHost, sender, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

            System.out.println("Mail sent succesfully!");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } finally {
        //Removing System properties
            sys_prop.remove("proxySet");
            sys_prop.remove("proxyHost");
            sys_prop.remove("proxyPort");
            sys_prop.remove("socksProxyHost");
            sys_prop.remove("mail.smtp.socketFactory.class");
            sys_prop.remove("mail.smtp.socketFactory.fallback");
            sys_prop.remove("mail.smtp.socketFactory.port");

        }

}

}

Property file 'Email.Properties':

[email protected]
[email protected]
password=*****
proxyHost=web-proxy.**.**.com
proxyPort= 8080
smtpHost=smtp.gmail.com
smtpPort=465

From the error I can understand that problem is in this part messageBodyPart.setContent(paragraphs, "application/msword"); where I am adding word document content to MIME message body part.

I have tried several other ways to achieve this but not able to do so. Please suggest a way to achieve this?


Solution

  • I got a resolution to this problem.Actually , I have to put different font face and font sizes in email body which I am trying to read from word document.To achieve this I have changed my approach,so instead of word document I have embedded my content into html tags which is quite simple :) , refer the below line of code which will replace word document part

    String htmltext = "+ Different Font Size

    + Different Font Size

    + "; messageBodyPart.setContent(htmltext, "text/html");

    During my research one of my friend suggested me following third party API's , it might be helpful to anyone

    http://www.oracle.com/technetwork/java/javamail/third-party-136965.html

    https://github.com/bbottema/simple-java-mail/