Desktop.Action.MAIL 为 mailto: 在 URI 中正确编码主题和正文字符串

发布于 2024-11-25 00:13:08 字数 2793 浏览 6 评论 0原文

我有一个特定于Java 6中的Java桌面API的问题,更具体地说是desktop.mail(URI uri)..

我想知道是否有一个函数可以用来确保f.ex中的主题和正文:

mailToURI =新 URI("mailto", getToEmails() + "?SUBJECT=" + getEmailSubject() + "&BODY=" + getEmailBody(), null);

桌面.mail(mailToURI);

将按照rfc2368保持并仍然在电子邮件应用程序中正确显示?

目前有问题的文本示例包括斯堪的纳维亚字母:æøå / ÆØÅ 以及在正文中添加包含与号 (&) 的复杂 URL 以及此类 f.ex:http://www.whatever.com?a=b&c=d 等等。Java

中是否有一个函数可以确保上述功能将 mailto: URI 方案与 Java Desktops mail(URI) 函数一起使用时是否保留了所寻求的完整性?

可以制作一个吗?

此时我已经尝试了我能想到的一切,包括:

  • MimeUtility.encodeText()
  • URLEncode.encode(..
  • 自定义函数encodeUnusualCharacters()

private static final Pattern SIMPLE_CHARS = Pattern.compile("[a-zA-Z0-9] ");

private String encodeUnusualChars(String aText) {
    StringBuilder result = new StringBuilder();
    CharacterIterator iter = new StringCharacterIterator(aText);
    for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
        char[] chars = {c};
        String character = new String(chars);
        if (isSimpleCharacter(character)) {
            result.append(c);
        } else {
            //hexEncode(character, "UTF-8", result);
        }
    }
    return result.toString();
}

private boolean isSimpleCharacter(String aCharacter) {
    Matcher matcher = SIMPLE_CHARS.matcher(aCharacter);
    return matcher.matches();
}

/**
For the given character and encoding, appends one or more hex-encoded characters.
For double-byte characters, two hex-encoded items will be appended.
 */
private static void hexEncode(String aCharacter, String aEncoding, StringBuilder aOut) {
    try {
        String HEX_DIGITS = "0123456789ABCDEF";
        byte[] bytes = aCharacter.getBytes(aEncoding);
        for (int idx = 0; idx < bytes.length; idx++) {
            aOut.append('%');
            aOut.append(HEX_DIGITS.charAt((bytes[idx] & 0xf0) >> 4));
            aOut.append(HEX_DIGITS.charAt(bytes[idx] & 0xf));
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LocalMail.class.getName()).log(Level.SEVERE, null, ex);
    }
}
  • 还有更多......

最好的情况是我最终会在打开的电子邮件中得到编码文本。

不提供任何特殊编码将导致 æøå 或类似内容停止进一步处理 也许

我觉得我错过了一些重要的东西。有人可以告诉我这个问题的解决方案吗?

对于换行符,我使用 String NL = System.getProperty("line.separator");

有一些系统特定的东西需要 顺便说一句,

我目前使用的是 Mac OS X 10.6.8,邮件 4.5

marius$ java -version java版本“1.6.0_26” Java(TM) SE 运行时环境(内部版本 1.6.0_26-b03-384-10M3425) Java HotSpot(TM) Client VM(build 20.1-b02-384,混合模式)

我真的觉得一定有办法 - 否则desktop.mail(URI)函数的主题和消息部分完全不可靠到了这样的程度无用。

非常感谢任何帮助我指明正确方向的帮助!

I have a question specific to the Java Desktop API in Java 6, more specifically desktop.mail(URI uri)..

I was wondering if there is a function one could use to ensure that the Subject and Body in f.ex:

mailToURI = new URI("mailto", getToEmails() + "?SUBJECT=" + getEmailSubject()
+ "&BODY=" + getEmailBody(), null);

desktop.mail(mailToURI);

will be kept in accordance with rfc2368 and still be displayed correctly in the email application?

Right now examples of problematic texts are the scandinavian letters: æøå / ÆØÅ and adding complex URLS in the Body containing ampersands (&) and such f.ex: http://www.whatever.com?a=b&c=d etc..

Is there a function in Java that ensures the aboved seeked integrity is preserved when using the mailto: URI scheme with Java Desktops mail(URI) function?

Would it be possible to make one?

At this point I have tried everything I can think of including:

  • MimeUtility.encodeText()
  • URLEncode.encode(..
  • A custom function encodeUnusualCharacters()

private static final Pattern SIMPLE_CHARS = Pattern.compile("[a-zA-Z0-9]");

private String encodeUnusualChars(String aText) {
    StringBuilder result = new StringBuilder();
    CharacterIterator iter = new StringCharacterIterator(aText);
    for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
        char[] chars = {c};
        String character = new String(chars);
        if (isSimpleCharacter(character)) {
            result.append(c);
        } else {
            //hexEncode(character, "UTF-8", result);
        }
    }
    return result.toString();
}

private boolean isSimpleCharacter(String aCharacter) {
    Matcher matcher = SIMPLE_CHARS.matcher(aCharacter);
    return matcher.matches();
}

/**
For the given character and encoding, appends one or more hex-encoded characters.
For double-byte characters, two hex-encoded items will be appended.
 */
private static void hexEncode(String aCharacter, String aEncoding, StringBuilder aOut) {
    try {
        String HEX_DIGITS = "0123456789ABCDEF";
        byte[] bytes = aCharacter.getBytes(aEncoding);
        for (int idx = 0; idx < bytes.length; idx++) {
            aOut.append('%');
            aOut.append(HEX_DIGITS.charAt((bytes[idx] & 0xf0) >> 4));
            aOut.append(HEX_DIGITS.charAt(bytes[idx] & 0xf));
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LocalMail.class.getName()).log(Level.SEVERE, null, ex);
    }
}
  • And many more...

At the best I end up with the encoded text in the email that is opened up.

Not providing any special encoding will cause æøå or similar to stop further processing of the content.

I feel I am missing something crucial. Could anyone please enlighten me with a solution to this?

For line breaks I use String NL = System.getProperty("line.separator");

Perhaps there is some System specific stuff that needs to be called to make this work??

By the way I am currently on Mac OS X 10.6.8 with Mail 4.5

marius$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03-384-10M3425)
Java HotSpot(TM) Client VM (build 20.1-b02-384, mixed mode)

I really feel there must be a way - otherwise the subject and message part of the desktop.mail(URI) function is completely unreliable to the point of being useless.

Any help to point me in the right direction is greatly appreciated!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谢谢 Marius,这是一行非常有用的代码。

为了性能我对其进行了一些修改...

当您不使用 RegExp 时,最好使用“replace”而不是“replaceAll”。

.replace("+", "%20")

比:

.replaceAll("\\+", "%20")

两者都替换所有出现更快,但第一个不必执行任何正则表达式解析。
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

另外,如果原始字符串已经有 \r\n 作为新行,则第二次替换将使 \r 加倍。这不是一个大问题,但我更喜欢删除该问题并提供正确的输入字符串:

String result = java.net.URLEncoder.encode(src, "utf-8").replace("+", "%20")

Thanks Marius, it's a very useful line of code.

I modified it a bit for performances...

It's better to use "replace" instead of "replaceAll", when you are not using RegExp.

This:

.replace("+", "%20")

is faster than:

.replaceAll("\\+", "%20")

Both replace ALL occurrences, but the first one does not have to do any regexp parsing.
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

Also, if the original string already has \r\n for new lines, the second replace will double the \r. It's not a big issue, but I prefer to remove that one and provide a proper input string:

String result = java.net.URLEncoder.encode(src, "utf-8").replace("+", "%20")
明媚殇 2024-12-02 00:13:08

试试这个,希望它对你有用。

String result = java.net.URLEncoder.encode(src, "utf-8").replaceAll("\\+", "%20").replaceAll("\\%0A", "%0D%0A");

Try this, hope it will work for you.

String result = java.net.URLEncoder.encode(src, "utf-8").replaceAll("\\+", "%20").replaceAll("\\%0A", "%0D%0A");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文