Reputation: 89
What i want to do is create an email link in a button such that when a user clicks the button it fires up default email client with my email address being the destination
I tried experimenting with this but no luck (I have no idea):
private void jButton50ActionPerformed(java.awt.event.ActionEvent evt) {
URL url = new URL('[email protected]');
}
But of course thats not a URL!
Update: I tried this and i'm getting errors whenever I try to use mail(). Do i have to import something else
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String mailTo = jButton2.getText();
URI uriMailTo = null;
try
{
if(mailTo.length() > 0)
{
uriMailTo = new URI("mailto", mailTo, null);
desktop.mail(uriMailTo);
}
else
{
desktop.mail();
}
}
catch(IOException e)
{
e.printStackTrace();
}
catch(URISyntaxException use)
{
use.printStackTrace();
}
}
Upvotes: 1
Views: 95
Reputation: 347214
Take a look at How to Integrate with the Desktop Class
This is an example taken directly from the above linked tutorial...
private void onLaunchMail(ActionEvent evt) {
String mailTo = txtMailTo.getText();
URI uriMailTo = null;
try {
if (mailTo.length() > 0) {
uriMailTo = new URI("mailto", mailTo, null);
desktop.mail(uriMailTo);
} else {
desktop.mail();
}
} catch(IOException ioe) {
ioe.printStackTrace();
} catch(URISyntaxException use) {
use.printStackTrace();
}
}
You should also take a look at Desktop#mail(URI)
, taking not of the required format of the URI
A mailto: URI can specify message fields including "to", "cc", "subject", "body", etc. See The mailto URL scheme (RFC 2368) for the mailto: URI specification details.
Updated with working example...
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class TestEmail {
public static void main(String[] args) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.MAIL)) {
String mailTo = "[email protected]";
URI uriMailTo = null;
try {
if (mailTo.length() > 0) {
System.out.println("Mail to " + mailTo);
uriMailTo = new URI("mailto", mailTo, "This is a message");
desktop.mail(uriMailTo);
} else {
System.out.println("Mail");
desktop.mail();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
}
}
}
Upvotes: 1