Search code examples
javaemailhtml-email

GWT Java email - java.io.UnsupportedEncodingException: text/html


I am sending an email with html text and an attachment and getting the error:

java.io.UnsupportedEncodingException: text/html

The code is:

public void emailMessage(String emailSubject, String message, String emailaddress, String imagePath) {  
    //Send an email
    try {

        //Send an email
        SimpleEmail email = new SimpleEmail();
        email.setHostName("mail.org");
        email.setSmtpPort(25); //No authentication required
        email.setFrom("address.org");
        email.addTo(emailaddress);
        email.setSubject(emailSubject);
        email.setCharset("utf-8");

        // Set the email message text.
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setText(message, "text/html");

        // Set the email attachment file
        FileDataSource fileDataSource = new FileDataSource(imagePath);

        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(fileDataSource));
        attachmentPart.setFileName(fileDataSource.getName());

        // Create Multipart E-Mail.
        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(messagePart);
        multipart.addBodyPart(attachmentPart);

        email.setContent(multipart);

        //Send the email
        email.send();

    } catch (EmailException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}

Initially I was sending an email without an attachment which worked. Then I added the multipart for the attachment and the text/html is no longer valid.


Solution

  • Try

    textPart.setText(text, "utf-8" );
    

    or

    htmlPart.setContent(html, "text/html; charset=utf-8" );