如何在Java中使用Runtime运行Unix程序? 到目前为止,这就是我的全部。我的计划是收发邮件的变化,以便我可以在不同接收者的循环中运行它。
Runtime run = Runtime.getRuntime();
Process mailx = run.exec("cat Docs/Mailmsgtmp.txt | mailx -s 'Subject' -r 'sender@mail.com' " + "reciever@mail.com");
答案 0 :(得分:1)
请勿使用Runtime.exec()
,请使用ProcessBuilder
。哦,Java也有用于发送邮件的库,所以你不需要使用外部命令......
无论如何,使用ProcessBuilder
,您可以轻松地重定向标准输入,这意味着您可以执行此操作:
// 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();
将此代码放入一个方法中,为什么不是Callable
,并检查返回代码。如果您想一次发送多封邮件,请使用ExecutorService
。
有关如何使用纯Java发送电子邮件的许多链接,请参阅here。
答案 1 :(得分:1)
您应该考虑使用Java的内置邮件包JavaMail。
来自http://www.tutorialspoint.com/java/java_sending_email.htm的简单示例:
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
有关详尽的文档,请参阅https://java.net/projects/javamail/pages/Home。