mail() - Launch Default Email Program

This section provides a tutorial example on how to use Desktop.mail() method to launch the default email program on the desktop of the operating system.



If you want to launch the default email program on the current desktop of the operating system, you can get the default Desktop object and call its mail() method. Here is a sample program:

/* DesktopSendEmail.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.net.URI;
public class DesktopSendEmail {
   public static void main(String[] a) {
      try {
		 String address = "herong_yang@yahoo.com";
		 String subject = "Java%20Swing%20Tutorials";
		 String body = "I%20like%20your%20tutorial%20book!";
         URI uri = new URI("mailto:"+address+"?subject="+subject
		    +"&body="+body);
         Desktop desktop = Desktop.getDesktop();
         if (desktop != null) desktop.mail(uri);
      } catch (Exception e) {
        e.printStackTrace();
      }
   }
}

Note that I have encoded the email address, subject and message body in the mailto URI string.

If you run this program, you will see the default email program is started with the given email content. On my Windows 10 computer, I am getting the Outlook app launched.

Launch Email Program on Desktop
Launch Email Program on Desktop



 

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

Integration with Desktop System

 javax.awt.Desktop and Related Methods

 browse() - Launch Default Web Browser

mail() - Launch Default Email Program

 edit() - Launch Default Editor for Given File

 Outdated Tutorials

 References

 Full Version in PDF/EPUB