2

我需要在 bash 中使用 sendmail 以 Java 发送我的电子邮件。由于配置重复,我无法使用 javamail...

    package fr.thales.edf.reportEmailAcrAcq.email;

    import java.io.IOException;

    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;

    public class SendHTMLEmail {
        private static final String SENDMAIL = "sendmail -R hdrs -N never -t -v <         ";
        private static final Logger LOGGER = Logger.getLogger(SendHTMLEmail.class
                .getName());

        private String fileName;

        public SendHTMLEmail(String fileName) {
            this.fileName = fileName;
        }

        public void sendMail() {
            String command = SENDMAIL + fileName;
            try {
                Runtime r = Runtime.getRuntime();
                LOGGER.log(Level.INFO, "Envoi de la commande: " + command);
                Process p = r.exec(command);
                p.waitFor();
                LOGGER.log(Level.INFO,
                        "Résultat de l'envoi de l'e-mail : " + p.getOutputStream());
            } catch (InterruptedException ex) {
                LOGGER.log(Level.FATAL, ex.getMessage());
            } catch (IOException ex) {
                LOGGER.log(Level.FATAL, ex.getMessage());
            }
        }
    }

这是我的日志文件:

    INFO - Command: sendmail -R hdrs -N never -t -v < ACR_20130111_100744.html

但是我的程序从不发送电子邮件,并且 sendmail 命令仍在运行(即使在 2 小时后)。另一件事,当我在 bash 脚本中使用相同的命令时,它会在 5 分钟内运行......

4

2 回答 2

1

我找到了解决方案:

    package fr.thales.edf.reportEmailAcrAcq.email;

    import java.io.IOException;

    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;

    public class SendHTMLEmail {
        private static final String SENDMAIL = "sendmail -R hdrs -N never -t -v < ";
        private static final Logger LOGGER = Logger.getLogger(SendHTMLEmail.class
                .getName());

        private String fileName;

        public SendHTMLEmail(String fileName) {
            this.fileName = fileName;
        }

        public void sendMail() {
            String command = SENDMAIL + fileName;
            try {
                Runtime r = Runtime.getRuntime();
                LOGGER.log(Level.INFO, "Envoi de la commande: " + command);
                Process p = r.exec(new String[]{"/usr/bin/ksh", "-c", command});
                p.waitFor();
                LOGGER.log(Level.INFO,
                        "Résultat de l'envoi de l'e-mail : " + p.getOutputStream());
            } catch (InterruptedException ex) {
                LOGGER.log(Level.FATAL, ex.getMessage());
            } catch (IOException ex) {
                LOGGER.log(Level.FATAL, ex.getMessage());
            }

        }
    }

我在这个论坛上找到了答案:http: //www.coderanch.com/t/379834/java/java/executing-shell-script-java

于 2013-01-11T10:10:38.903 回答
0

当您从 Java 创建一个流程时,您还必须处理它的输入和输出流。特别是,Process除非您从 STDOUT 和 STDERR 读取它的所有输出,否则 a 可能不会终止。以下是常见问题的描述;你似乎正在遭受第一个的痛苦。

于 2013-01-11T09:52:28.180 回答