Eclipse SWT – Creating an email in the default email client

As many of you properly know SWT has the nice Program.launch() method which allows to start programs associated with an URI.

Example:

// This works for Windows
	public void openMailWindows(String to, String subject,String body, List<File> attachments) {
		String mailto = "mailto:" + enc(to) + "?subject=" + enc(subject) + "&body=" + enc(body);
		for (File f : attachments) {
			mailto += "&attach=" + f.getAbsolutePath();
		}
		Program.launch(mailto);
	}

	private String enc(String p) {
		if (p == null)
			p = "";
		try {
			return URLEncoder.encode(p, "UTF-8").replace("+", "%20");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException();
		}
	}

Unfortunately this does not seem to be working on Linux. So if you are working under Linux you have to use the Java runtime directly. Unfortunately this requires you in my humble opinion to code against a a specific application.

// This works for Linux with Thunderbird
	public void openMailLinux(String to, String subject,String body, List<File> attachments) {
		String mailto = "mailto:" + enc(to) + "?subject=" + enc(subject) + "&body=" + enc(body);
		for (File f : attachments) {
			mailto += "&attach=" + f.getAbsolutePath();
		}
		Program.launch(mailto);
		try {
			// For using the parameters check the following description
			// http://kb.mozillazine.org/Command_line_arguments_%28Thunderbird%29
			Runtime.getRuntime().exec("thunderbird -compose");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

I hope this helps.

You find me also on Twitter and Google+.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Eclipse and tagged , . Bookmark the permalink.

2 Responses to Eclipse SWT – Creating an email in the default email client

  1. Mahmoud says:

    On linux, it should be like this:

    Program.launch(“xdg-open” + mailto);

  2. Instead of thunderbird you can use the xdg-open program to open the mailto link using the user’s preferred mail application.

    Eclipse should be using xdg-open (or gnome-open if it’s not found) inside Program.launch though. It might be worth filing a bug.

Comments are closed.