Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 390
Kulwant Avatar asked Oct 13 '11 21:10

Kulwant


People also ask

How do you add a link to an email in Java?

If you want the link to be clickable in the mail, you should send the mail as HTML. Show activity on this post. A couple of things need to happen for this to work.

How do you put a link in the body of an email?

Insert a hyperlinkIn a message, position the cursor in the message body where you want to add a link. On the Message tab, click Hyperlink. In the Link box, type the address for the link. In the Text box, type the text that you want to appear in your message.

How do you add a link to a string in Java?

Creating a HyperlinkHyperlink link = new Hyperlink(); link. setText("http://example.com"); link. setOnAction((ActionEvent e) -> { System. out.


2 Answers

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

like image 187
smat Avatar answered Oct 11 '22 06:10

smat


A couple of things need to happen for this to work.

  1. Send the link as html
  2. Set the content type to text/html

String text = "Test\n" + text +"\nVisit <a href="http://test.com">Test.com</a>"; messageBodyPart.setContent(text, "text/html");

From JavaMail API FAQ

Q: How do I send HTML mail? A: There are a number of demo programs included with the distribution that show how to send HTML mail. If you want to send a simple message that has HTML instead of plain text, see the sendhtml.java program in the demo directory. If you want to send an HTML file as an attachment, see the sendfile.java example that shows how to send any file as an attachment.

like image 44
Jonathan Spooner Avatar answered Oct 11 '22 08:10

Jonathan Spooner