alexander
alexander

Reputation: 1342

Run linux command in java to send email with quotes

I am able to send emails in Linux via commandline:

cat < x.txt | mail -s "SUBJECT" [email protected]

This works perfectly. Note: The body is in x.txt.

Now, I want to execute exactly this command with Java.

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

    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);

Well, It is not working and I am getting following error.

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

Am I splitting those command(s) wrong?

How can I execute this command properly?

Upvotes: 0

Views: 3581

Answers (2)

EvenLisle
EvenLisle

Reputation: 4812

Try to write a script and execute it, rather than execute separate commands:

String email = "[email protected]"; // 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);

Pipe (|) is a shell built-in, and not an actual unix command as such.

Upvotes: 6

SMA
SMA

Reputation: 37023

You should probably be doing something like:

Process p = Runtime.getRuntime().exec("/usr/sbin/sendmail .. [email protected]");
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();

Also note, you have javamail api already available, so make sure you make your code platform independent by using such libraries.

Upvotes: 0

Related Questions