在java中运行linux命令以发送带引号的电子邮件

时间:2015-04-18 11:21:41

标签: java linux

我可以通过命令行在Linux上发送电子邮件:

cat < x.txt | mail -s "SUBJECT" email@email.com

这完美无缺。注意:正文位于x.txt

现在,我想用Java执行这个命令。

Process p = Runtime.getRuntime().exec(
            new String[] { "cat < x.txt", "|", "mail -s", "SUBJECT",
                    "email@email.com" });

    p.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(
            p.getInputStream()));
    String line = "";
    String output = "";

    while ((line = buf.readLine()) != null) {
        output += line + "\n";
    }

System.out.println(output);

嗯,它无法正常工作,我遇到了错误。

Exception in thread "main" java.io.IOException: Cannot run program "cat < x.txt |": error=2, Datei oder Verzeichnis nicht gefunden
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at java.lang.Runtime.exec(Runtime.java:620)
        at java.lang.Runtime.exec(Runtime.java:485)
        at test.main(test.java:9) Caused by: java.io.IOException: error=2, Datei oder Verzeichnis nicht gefunden
        at java.lang.UNIXProcess.forkAndExec(Native Method)
        at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
        at java.lang.ProcessImpl.start(ProcessImpl.java:134)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 3 more

我错误地将这些命令拆分了吗?

如何正确执行此命令?

2 个答案:

答案 0 :(得分:6)

尝试编写脚本并执行它,而不是执行单独的命令:

String email = "email@email.com"; // Or any way of entering the email address
String[] command = {"/bin/sh", "-c", "cat < x.txt | mail -s SUBJECT" +  email};
Process p = Runtime.getRuntime().exec(command);

管道(|)是内置的shell,而不是实际的unix命令。

答案 1 :(得分:0)

你应该做的事情如下:

Process p = Runtime.getRuntime().exec("/usr/sbin/sendmail .. email@email.com");
OutputStream os = p.getOutputStream();
InputStream is = new FileInputStream("x.txt");
// copy the contents
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) != -1) {
    os.write(buf, 0, len); // only write as many as you have read
}
os.close();
is.close();

另请注意,您已经有javamail api,因此请确保使用此类库使您的代码平台独立。