how do I run Unix programs with Runtime in Java? So far this is all I have. My plans are for the reciever mail to be varied so that I can run this in a loop with different recievers.
Runtime run = Runtime.getRuntime();
Process mailx = run.exec("cat Docs/Mailmsgtmp.txt | mailx -s 'Subject' -r 'sender@mail.com' " + "reciever@mail.com");
Don't use Runtime.exec()
, use a ProcessBuilder
. Oh, and Java also has libraries for sending mails, so you needn't use an external command...
Anyway, with a ProcessBuilder
you can redirect the standard input easily, which means in your case you can do this:
// recipient is the email address of the... recipient
final ProcessBuilder pb = new ProcessBuilder("mailx", "-r",
"sender@foo.com", recipient);
final Path textToSend = Paths.get("Docs/mailtext.txt").toRealPath();
pb.redirectInput(textToSend.toFile());
// Also redirect stdout and stderr somewhere
final Process p = pb.start();
return p.waitFor();
Put this code into a method which can be, why not, a Callable
and check for the return code. Use an ExecutorService
if you want to send several mails at once.
See here for many, many links on how to use pure Java to send emails.