0

I'm currently working on a project for school and I'm trying to use sSMTP to send emails from java to a user using a text file. Executing from the command line ssmtp email@gmail.com < msg.txt works just fine and sends me the email with the information contained in msg.txt. However, when I try to do it in java using ProcessBuilder it doesn't send an email.

`ProcessBuilder builder = new ProcessBuilder;
 builder.command("ssmtp", "email@gmail.com", "<", "msg.txt");
 Process p = builder.start();`

I believe that it doesn't like where I try to pipe in msg.txt. If anyone knows a better way to do this that would be great. I haven't been able to find anything yet and am not sure how to do it myself

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
Genative
  • 3
  • 3

1 Answers1

1

Instead of trying to rely on the shell's redirect functionality (which as you see doesn't work), you can just read msg.txt and write it to the process' OutputStream. It'll be the same thing, but in code (and it'll be a better solution too).

Something along the lines of

Process p = new ProcessBuilder("ssmtp").start();
PrintStream out = new PrintStream(p.getOutputStream());
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("msg.txt")));
while((line = in.readLine()) != null)
    out.println(line);
out.close();
in.close();

However if you want to use shell redirection which I wouldn't recommend for anything serious, you need to execute the program which actually does the redirection, i.e. bash. The following should do the trick:

new ProcessBuilder("bash", "ssmtp", "email@gmail.com", "<", "msg.txt").start();

As dave_thompson_085 commented, it's even easier to do programmatic redirection. Things sure are easy these days!

new ProcessBuilder("ssmtp", "email@gmail.com").redirectInput(new File("msg.txt")).start();
Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Thank you so much! I didn't even think to just read the file in. The only thing I needed to change was in the first line I needed to add the destination of the email as a command. – Genative Mar 12 '18 at 01:33
  • 1
    Since j7 ProcessBuilder can do redirection, but using method calls not the shell anglebracket syntaxes; see the javadoc. (The older more basic Runtime.exec can't.) – dave_thompson_085 Mar 12 '18 at 02:53