Search code examples
javajakarta-mail

Javamail and adding link to text


I am using Javamail. Within the MimeMessage.setText, I have to include code that encodes text as a URL. For the purposes like below.

BodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setText("Test\n" + text +"\nVisit Test.com");`

In this I need Test.com to be embedded as a URL. Is there a tag or wildcard that would do this? Thanks.

Basically I would prefer to avoid using html in the javamail and utilizing the following.

Test.com


Solution

  • If you want the link to be clickable in the mail, you should send the mail as HTML.

    To do this, you should try to create an HTML MIME mail:

    InternetHeaders headers = new InternetHeaders();
    headers.addHeader("Content-type", "text/html; charset=UTF-8");
    String html = "Test\n" + text + "\n<a href='http://test.com'>Test.com</a>";
    MimeBodyPart body = new MimeBodyPart(headers, html.getBytes("UTF-8"));
    

    EDIT:

    It is also possible to use setText when sending HTML-mail:

    String html = "Test\n" + text + "\n<a href='http://test.com'>Test.com</a>";
    messageBodyPart.setText(html, "UTF-8", "html");
    

    See the the API for more details