Search code examples
javaemailhtml-emailapache-commonsemail-attachments

setting HTML text in MultiPartEmail


I have java code for sending email with attachment as below.

String myEmailId = "xx@yahoo.co.in";
String myPassword = "@xx";
String senderId = "yy@gmail.com";
try {
    MultiPartEmail email = new MultiPartEmail();
    email.setSmtpPort(587);
    email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
    email.setDebug(true);
    email.setHostName("smtp.mail.yahoo.com");
    email.addTo(senderId);
    email.setFrom(myEmailId);
    email.setSubject("The picture");
    email.setMsg("<font face='verdana' size='3'>Here is the picture you wanted "
            + "<table>"
            + "<tr><th>id</th><th>Name</th></tr>"
            + "<tr><th>1</th><th>Name 1</th></tr>"
            + "<tr><th>2</th><th>Name 2</th></tr>"
            + "<tr><th>3</th><th>Name 3</th></tr>"
            + "<tr><th>4</th><th>Name 4</th></tr>"
            + "</table>"
            + "</font>");

    // add the attachment
    EmailAttachment attachment = new EmailAttachment();
    attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test_small.pdf");
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    email.attach(attachment);

    attachment = new EmailAttachment();
    attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test.pdf");
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    email.attach(attachment);

    // send the email
    email.send();
    System.out.println("Mail sent!");
} catch (Exception e) {
    System.out.println("Exception :: " + e);
}

All is working fine EXCEPT, the HTML code is displaying as it is.

In Email what I get is

<font face='verdana' size='3'>Here is the picture you wanted <table><tr><th>id</th><th>Name</th></tr><tr><th>1</th><th>Name 1</th></tr><tr><th>2</th><th>Name 2</th></tr><tr><th>3</th><th>Name 3</th></tr><tr><th>4</th><th>Name 4</th></tr></table></font>

Is there any parameter, email that I will receive will have proper HTML formatted data.

Note :

Actually I was using Email email = new SimpleEmail(); and doing above stuff where HTML part is working perfectly. However when I had to switch to attachment, I had to use MultiPartEmail email = new MultiPartEmail();.


Solution

  • I got answer.

    Just changed MultiPartEmail email = new MultiPartEmail(); to MultiPartEmail email = new HtmlEmail();