23

我目前正在寻找一种方法(在 Java 中)来启动具有定义的接收者、主题和正文以及预定义附件的默认邮件客户端。

由于 RFC 的限制,java.awt.Desktop.mail-Method 不适用于附件。JDIC 项目已死,JMAPI 项目在构建过程中相当模糊。(需要 1.4 Mozilla-Sources)而且我必须自己为 64 位系统构建它。

有替代方案吗?我已经阅读了这里的文章,但是使用 rundl32.dll 和这样的“解决方案”并不是我想要放入生产代码的东西。

4

3 回答 3

6

There does not appear to be any OS agnostic method of doing this in Java as not all OSes provide a standard way to launch the default e-mail application with more than the basic fields for a new email.

On Windows, it is possible to use a JNI interface to MAPI, which will provide more control over opening an email in a mail application. As you mentioned, one such library is JMAPI - however, it appears there are many libraries by such a name with similar purposes. I discovered one that is recently maintained and seems fairly straight-forward. It includes a pre-built binary dll and an accompanying Java JNI-based library.

https://github.com/briandealwis/jmapi

With this code, it seems you would only need to construct a message object and call a method to launch it in a mail application: import jmapi.*; ...

    if (JMAPI.isMapiSupported()) {
        Message msg = new Message();
        msg.setSubject("test!");
        msg.setBody("Hello world");

        List<String> toAddresses = new LinkedList<String>();
        toAddresses.add("example@example.com");
        msg.setToAddrs(toAddresses);

        List<String> attachPaths = new LinkedList<String>();
        //Must be absolute paths to file
        attachPaths.add("C:\Users\Documents\file.jpg");
        msg.setAttachments(attachPaths);

        JMAPI.open(msg);
    }

Another possibility that might work for Windows and Mac (and potentially other OSes) is to generate a ".eml" or ".msg" file with the content and attachments you would like to include already encoded as part of the email. This file could then be launched with the default handler for the respective email file format. However, this is not guaranteed to open the default email handler, nor is the file format going to be compatible with everyone email client.

于 2011-05-23T06:48:15.787 回答
0

(据我所知)目前无法添加预定义的附件,但您可以使用 java.awt.Desktop.mail 执行您提到的其他操作(使用定义的接收者、主题和正文启动默认邮件客户端)。 . 我相信你已经在这里检查过了。不过,这将非常有用。

于 2011-05-22T11:51:09.803 回答
0

现在可能为时已晚,但以防万一有人仍然发现这个问题:

Desktop.getDesktop().mail(new URI("mailto:email@example.com?subject=attachment_example&body=see_attached_file&attachment=/path/to/attachment"));

应该以独立于平台的方式来解决问题。

于 2017-09-22T12:42:28.913 回答