使用Apache Commons电子邮件在我的硬盘上发送带有附件的邮件

时间:2018-12-12 10:33:43

标签: java-8 apache-commons-email

我在使用Apache Commons电子邮件在邮件中发送附件时遇到问题。 为了方便快速地进行解释,我发送了邮件,但是在Outlook中查看邮件时根本没有附件。

我使用Apache Commons电子邮件v1.4和JAVA 8。 我想在硬盘驱动器上的此位置C:\ myfolder \ myfile.log

上添加一个日志文件。

到目前为止,这是我尝试添加的附件

Path logRejetPath = Paths.get("C:\\myfolder\\myfile.log");
Boolean pathExists = Files.exists(logRejetPath, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});

if (pathExists) {
   File rejLogFile = new File(logRejetPath.toString());
   email.attach(new FileDataSource(rejLogFile), "test", "test");                
}
email.send();

Path logRejetPath = Paths.get("C:\\myfolder\\myfile.log");
Boolean pathExists = Files.exists(logRejetPath, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});

if (pathExists) {
   File rejLogFile = new File(logRejetPath.toString());
   email.attach(rejLogFile);                
}
email.send();

Path logRejetPath = Paths.get("C:\\myfolder\\myfile.log");
Boolean pathExists = Files.exists(logRejetPath, new LinkOption[]{LinkOption.NOFOLLOW_LINKS});

if (pathExists) {
    EmailAttachment attachment = new EmailAttachment();
    attachment.setPath(logRejetPath.toString());
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    attachment.setDescription("test");
    attachment.setName("test");
    email.attach(attachment);              
}
email.send();

我的精确电子邮件是这样创建的MultiPartEmail对象:

MultiPartEmail email = new MultiPartEmail();

    try {
        email.setHostName(config.getSmtpHost()); 
        email.setSmtpPort(Integer.valueOf(config.getSmtpPort()));
        if (!config.getSmtpUser().isEmpty()) {
            email.setAuthenticator(
                    new DefaultAuthenticator(config.getSmtpUser(), config.getSmtpPwd()));
            email.setSSLOnConnect(true);
        } else {
            email.setSSLOnConnect(false);
        }
        email.setCharset("utf-8");
        email.setFrom("me@me.fr");
        email.setSubject("subjectforemail");
        email.setContent(this.getMessage(), "text/html");

        final String[] destinataires = config.getMailDestinataires().split(";");
        for (final String dest : destinataires) {
            email.addTo(dest);
        }

每次使用这些不同的方法添加附件时,我都会收到带有邮件的电子邮件,但没有附件。每次变量pathExists为TRUE,每次我都没有错误。

感谢您将来的回答和帮助。

编辑:通过更改此内容找到解决方案:

MultiPartEmail email = new MultiPartEmail();

由此:

HtmlEmail email = new HtmlEmail();

1 个答案:

答案 0 :(得分:0)

通过更改此方法找到的解决方案:

MultiPartEmail email = new MultiPartEmail();

由此:

HtmlEmail email = new HtmlEmail();