在java中,如何使用sendmail发送电子邮件?

时间:2013-01-11 09:44:22

标签: java bash sendmail

我需要在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分钟内工作......

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

从Java创建进程时,还必须处理其输入和输出流。特别是,除非您从STDOUT和STDERR读取其所有输出,否则Process可能不会终止。 Here是对常见问题的描述;你好像是第一个受苦了。