windows 如何以跨平台的方式打开带有主题和正文的默认邮件程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I open the default mail program with a Subject and Body in a cross-platform way?
提问by Frank Krueger
How do I open the default mail program with a Subject and Body in a cross-platform way?
如何以跨平台的方式打开带有主题和正文的默认邮件程序?
Unfortunately, this is for a a client app written in Java, not a website.
不幸的是,这是针对用 Java 编写的客户端应用程序,而不是网站。
I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever.
我希望它以跨平台的方式工作(这意味着 Windows 和 Mac,对不起 Linux)。我很高兴在 Windows 中执行 VBScript,或者在 OS X 中执行 AppleScript。但我不知道这些脚本应该包含什么。我很想执行用户的默认程序,而不是只搜索 Outlook 或其他任何东西。
In OS X, I have tried executing the command:
在 OS X 中,我尝试执行命令:
open mailto:?subject=MySubject&body=TheBody
URL escaping is needed to replace spaces with %20
.
需要 URL 转义以将空格替换为%20
.
UpdatedOn Windows, you have to play all sorts of games to get start
to run correctly. Here is the proper Java incantation:
更新在 Windows 上,您必须玩各种游戏才能start
正确运行。这是正确的 Java 咒语:
class Win32 extends OS {
public void email(String subject, String body) throws Exception {
String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\"";
Runtime.getRuntime().exec(cmd);
}
}
采纳答案by rotabla
In Java 1.6 you have a stardard way to open the default mailer of the platform: the Desktop.mail(URI) method.The URI can be used to set all the fields of the mail (sender, recipients, body, subject). You can check a full example of desktop integration in Java 1.6 on Using the Desktop API in Java SE 6
在 Java 1.6 中,您有一种标准的方式来打开平台的默认邮件程序: Desktop.mail(URI) 方法。URI 可用于设置邮件的所有字段(发件人、收件人、正文、主题)。您可以在使用 Java SE 6 中的桌面 API上查看Java 1.6 中桌面集成的完整示例
回答by travis
start
works fine in Windows (see below). I would use Java's built in UrlEscape then just run a second replacement for '+' characters.
start
在 Windows 中工作正常(见下文)。我会使用内置在 UrlEscape 中的 Java,然后运行第二个替换 '+' 字符。
start mailto:"?subject=My%20Subject&body=The%20Body"
回答by Dhaust
1. Add a Subject Line
1. 添加主题行
You can prefill the subject line in the email by adding the subject preceded by '?subject=' after the email address.
您可以通过在电子邮件地址后添加以“ ?subject=' ”开头的主题来预填充电子邮件的主题行。
So the link now becomes:
所以链接现在变成:
<a href="mailto:[email protected]?subject=Mail from Our Site">Email Us</a>
2. Send to Multiple Recipients
2. 发送给多个收件人
Mail can be sent to additional recipients either as carbon copies (cc) or blind carbon copies (bcc).
邮件可以以抄送 (cc) 或密件抄送 (bcc) 的形式发送给其他收件人。
This is done in a similar way, by placing '[email protected]' after the initial address.
这以类似的方式完成,通过在初始地址之后放置“ [email protected]”。
So the link looks like this:
所以链接看起来像这样:
<a href="mailto:[email protected][email protected]">Email Us</a>
cc can simply be replaced by bcc if you wish to send blind carbon copies.
如果您想发送密件抄送,cc 可以简单地替换为 bcc。
This can be very useful if you have links on pages with different subjects. You might have the email on each page go to the appropriate person in a company but with a copy of all mails sent to a central address also.
如果您在不同主题的页面上有链接,这将非常有用。您可能将每页上的电子邮件发送给公司中的相应人员,但也将所有邮件的副本发送到一个中央地址。
You can of course specify more than one additional recipient, just separate your list of recipients with a comma.
您当然可以指定多个额外的收件人,只需用逗号分隔您的收件人列表。
<a href="mailto:[email protected][email protected], [email protected], [email protected]">Email Us</a>
Sourced from Getting More From 'mailto'which now 404s. I retrieved the content from waybackmachine.
源自从“mailto”获取更多信息,现在是 404。我从 waybackmachine 检索了内容。
3. Combining Code
3. 组合代码
You can combine the various bits of code above by the addition of an '&' between each.
您可以通过在每个代码之间添加一个“&”来组合上面的各种代码。
Thus adding
因此添加
[email protected]?subject=Hello&[email protected]&[email protected]
would send an email with the subject 'Hello' to me, you and her.
会向我、你和她发送一封主题为“你好”的电子邮件。
4. Write the Email
4. 写电子邮件
You can also prefill the body of the email with the start of a message, or write the whole message if you like! To add some thing to the body of the email it is again as simple as above - '?body=' after the email address. However formatting that email can be a little tricky. To create spaces between words you will have to use hex code - for example '%20' between each word, and to create new lines will mean adding '%0D'. Similarly symbols such as $signs will need to be written in hex code.
您还可以使用消息的开头预填充电子邮件的正文,或者如果您愿意,可以写下整个消息!要将某些内容添加到电子邮件的正文中,就像上面一样简单 -在电子邮件地址之后添加“ ?body=' ”。但是,格式化该电子邮件可能有点棘手。要在单词之间创建空格,您必须使用十六进制代码 - 例如在每个单词之间使用“ %20”,创建新行意味着添加“ %0D”。同样,$符号等符号也需要用十六进制代码编写。
If you also wish to add a subject line and send copies to multiple recipients, this can make for a very long and difficult to write bit of code.
如果您还希望添加一个主题行并将副本发送给多个收件人,这可能会使编写代码的时间变得非常长且困难。
It will send a message to three people, with the subject and the message filled in, all you need to do is add your name.
它将向三个人发送消息,填写主题和消息,您需要做的就是添加您的姓名。
Just look at the code!
只看代码!
<a href="mailto:[email protected][email protected]
&[email protected]&Subject=Please%2C%20I%20insist
%21&Body=Hi%0DI%20would%20like%20to%20send%20you%20
%241000000%20to%20divide%20as%20you%20see%20fit%20among
%20yourselves%20and%20all%20the%20moderators.%0DPlease%
20let%20me%20know%20to%20whom%20I%20should%20send
%20the%20check.">this link</a>
Note: Original source URL where I found this is now 404ing so I grabbed to content from waybackmachineand posted it here so it doesn't get lost. Also, the OP stated it was not for a website, which is what these examples are, but some of these techniques may still be useful.
注意:我发现它的原始源 URL 现在是 404ing,所以我从 waybackmachine 抓取内容并将其张贴在这里,这样它就不会丢失。此外,OP 表示它不适用于网站,这就是这些示例的内容,但其中一些技术可能仍然有用。
回答by Shadow2531
I don't know if Java has some built-in method for urlencoding the string, but this link http://www.permadi.com/tutorial/urlEncoding/shows some of the most common chars to encode:
我不知道 Java 是否有一些用于对字符串进行 urlencoding 的内置方法,但是这个链接http://www.permadi.com/tutorial/urlEncoding/显示了一些最常见的编码字符:
For percent-encoding mailto URI hnames and hvalues, I use the rules at http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#encoding. Under http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#implementations, there's a Java example that may help.
对于百分比编码的 mailto URI hnames 和 hvalues,我使用http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#encoding 上的规则。在http://shadow2531.com/opera/testcases/mailto/modern_mailto_uri_scheme.html#implementations 下,有一个 Java 示例可能会有所帮助。
Basically, I use:
基本上,我使用:
private String encodex(final String s) {
try {
return java.net.URLEncoder.encode(s, "utf-8").replaceAll("\+", "%20").replaceAll("\%0A", "%0D%0A");
} catch (Throwable x) {
return s;
}
}
The string that's passed in should be a string with \r\n, and stray \r already normalized to \n.
传入的字符串应该是带有\r\n 的字符串,并且杂散\r 已经标准化为\n。
Also note that just returning the original string on an exception like above is only safe if the mailto URI argument you're passing on the command-line is properly escaped and quoted.
另请注意,仅当您在命令行上传递的 mailto URI 参数被正确转义和引用时,仅在上述异常中返回原始字符串才是安全的。
On windows that means:
在 Windows 上,这意味着:
- Quote the argument.
- Escape any " inside the quotes with \.
- Escape any \ that precede a " or the end of the string with \.
- 引用论点。
- 用 \ 转义引号内的任何 " 。
- 使用 \ 转义 " 之前的任何 \ 或字符串的结尾。
Also, on windows, if you're dealing with UTF-16 strings like in Java, you might want to use ShellExecuteW to "open" the mailto URI. If you don't and return s on an exception (where some hvalue isn't completely percent-encoded, you could end up narrowing some wide characters and losing information. But, not all mail clients accept unicode arguments, so ideally, you want to pass a properly percent-encoded-utf8 ascii argument with ShellExecute.
此外,在 Windows 上,如果您像在 Java 中一样处理 UTF-16 字符串,您可能希望使用 ShellExecuteW 来“打开”mailto URI。如果您不这样做并返回 s 异常(其中某些 hvalue 不是完全百分比编码的,您最终可能会缩小一些宽字符并丢失信息。但是,并非所有邮件客户端都接受 unicode 参数,因此理想情况下,您希望使用 ShellExecute 传递正确的百分比编码的 utf8 ascii 参数。
Like 'start', ShellExecute with "open" should open the mailto URI in the default client.
像'start'一样,带有“open”的ShellExecute应该在默认客户端打开mailto URI。
Not sure about other OS's.
不确定其他操作系统。
回答by Chris Hanson
Never use Runtime.exec(String)
on Mac OS X or any other operating system. If you do that, you'll have to figure out how to properly quote all argument strings and so on; it's a pain and very error-prone.
切勿Runtime.exec(String)
在 Mac OS X 或任何其他操作系统上使用。如果你这样做,你就必须弄清楚如何正确引用所有参数字符串等等;这很痛苦,而且很容易出错。
Instead, use Runtime.exec(String[])
which takes an array of already-separated arguments. This is much more appropriate for virtually all uses.
相反,使用Runtime.exec(String[])
which 接受一组已经分隔的参数。这几乎适用于所有用途。
回答by Ryan Farley
I had to re-implement URLencode because Java's would use + for space and Mail took those literally.
我不得不重新实现 URLencode,因为 Java 会使用 + 来表示空格,而 Mail 从字面上理解这些。
I don't know if Java has some built-in method for urlencoding the string, but this link http://www.permadi.com/tutorial/urlEncoding/shows some of the most common chars to encode:
我不知道 Java 是否有一些用于对字符串进行 urlencoding 的内置方法,但是这个链接http://www.permadi.com/tutorial/urlEncoding/显示了一些最常见的编码字符:
; %3B
? %3F
/ %2F
: %3A
# %23
& %24
= %3D
+ %2B
$ %26
, %2C
space %20 or +
% %25
< %3C
> %3E
~ %7E
% %25
回答by Ryan Farley
Mailto isn't a bad route to go. But as you mentioned, you'll need to make sure it is encoded correctly.
Mailto 是一条不错的路线。但是正如您所提到的,您需要确保它的编码正确。
The main problem with using mailto is with breaking lines. Use %0A for carriage returns, %20 for spaces.
使用 mailto 的主要问题是断行。使用 %0A 表示回车,使用 %20 表示空格。
Also, keep in mind that the mailto is considered the same as a URL of sorts and therefore will have the same limitations for length. See http://support.microsoft.com/kb/208427, note the maximum URL length of 2083 characters. This is confirmed for mailto as well in this article: http://support.microsoft.com/kb/279460/en-us. Also, some mail clients can also have a limit (I believe older versions of Outlook Express had a limit of something much smaller like 483 characters or something. If you expect to have a longer string than that then you'll need to look at alternatives.
另外,请记住,mailto 被认为与各种 URL 相同,因此将具有相同的长度限制。请参阅 http://support.microsoft.com/kb/208427,注意最大 URL 长度为 2083 个字符。这在本文中也对 mailto 进行了确认:http: //support.microsoft.com/kb/279460/en-us。此外,某些邮件客户端也可能有限制(我相信旧版本的 Outlook Express 的限制要小得多,例如 483 个字符之类的。如果您希望有比这更长的字符串,那么您需要查看替代方案.
BTW, you shouldn't have to resort to kicking out a script to do that as long as you can shell out a command from Java (I don't know if you can since I don't do Java).
顺便说一句,只要您可以从 Java 中执行命令,您就不必求助于踢出脚本来执行此操作(我不知道您是否可以,因为我不使用 Java)。
回答by NoNaMe
You may use this...
你可以用这个...
main(string[] args){
String forUri = String.format("mailto:?subject=%s&body=%s", urlEncode(sub), urlEncode(mailBody));
Desktop.getDesktop().mail(new URI(forUri));
}
private static final String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8").replace("+", "%20");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
Also for formatting read A simple way of sending emails in Java: mail-to links
也用于格式化阅读在 Java 中发送电子邮件的简单方法:mail-to 链接
回答by Frank Krueger
I have implemented this, and it works well on OS X. (Ryan's mention of the max URL length has not been codified.)
我已经实现了这个,它在 OS X 上运行良好。(Ryan 提到的最大 URL 长度尚未编纂。)
public void email(String subject, String body) throws Exception {
String cmd = "open mailto:";
cmd += "?subject=" + urlEncode(subject);
cmd += "&body=" + urlEncode(body);
Runtime.getRuntime().exec(cmd);
}
private static String urlEncode(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isLetterOrDigit(ch)) {
sb.append(ch);
}
else {
sb.append(String.format("%%%02X", (int)ch));
}
}
return sb.toString();
}
I had to re-implement URLencode because Java's would use +
for space and Mail took those literally. Haven't tested on Windows yet.
我不得不重新实现 URLencode,因为 Java 将+
用于空间,而 Mail 从字面上理解这些。还没有在 Windows 上测试过。