我想在点击菜单时发送电子邮件。
MenuItem sendmail= new MenuItem("Send E-Mail");
sendmail.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
// Call E-mail Client
}
});
您能告诉我如何通过此代码调用安装到用户PC的电子邮件客户端吗?
答案 0 :(得分:4)
这是未记录的,但似乎有效,并且是一种“纯FX”解决方案,而不是依赖于java.awt API或了解外部可执行文件的位置。调用Application.getHostServices().showDocument(...)
方法并传入mailto:url作为网址:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class OpenDefaultBrowser extends Application {
@Override
public void start(Stage primaryStage) {
final HBox root = new HBox(5);
final TextField textField = new TextField("help@example.com");
final Button goButton = new Button("Mail");
EventHandler<ActionEvent> goHandler = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
getHostServices().showDocument("mailto:"+textField.getText());
}
};
textField.setOnAction(goHandler);
goButton.setOnAction(goHandler);
root.getChildren().addAll(textField, goButton);
final Scene scene = new Scene(root, 250, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
答案 1 :(得分:3)
您可以使用Desktop类。我相信代码看起来像:
import java.awt.Desktop;
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.MAIL)) {
URI mailto = new URI("mailto:john@example.com?subject=Hello%20World");
desktop.mail(mailto);
}
}
答案 2 :(得分:0)
如果您只想启动代表电子邮件客户端的单独进程,请使用java.lang.Runtime.exec(请参阅http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html)或者如果要嵌入客户端,请使用Java Mail API (http://www.oracle.com/technetwork/java/javamail/index.html)