添加附件的Javamail会阻止发送邮件

时间:2017-08-24 17:43:35

标签: java email javamail attachment

我正在努力使用Javamail,我正在尝试发送附带zip文件的电子邮件。 当我尝试发送没有附件的邮件时,它工作正常,但是当我添加zip时,邮件不再发送。我没有错误......

我的代码:

LOGGER.info("########################### Send Email with attachement to " + destination + "  Start ######################");
    //Config smtp mail
    Properties props = new Properties();
    props.put("mail.smtp.host", getSmtpHost());
    props.put("mail.smtp.socketFactory.port", getSmtpsocketFactoryPort());
    props.put("mail.smtp.socketFactory.class", getSmtpsocketFactoryClass());
    props.put("mail.smtp.auth", getSmtpAuth());
    props.put("mail.smtp.port", getSmtpPort());

    //instance Session
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(getUsername(), getPassword());
        }
    });

    try {
        //construction objet mail
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(getFromAddress()));

        //Send Email to Addresse
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination));
        message.setSubject(objet);
        message.setSentDate(new Date());

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(contenu);

        MimeBodyPart  attachmentBodyPart = new MimeBodyPart();
        String fileName = attachementPath + attachementName;
        File file = new File (fileName);
        attachmentBodyPart.attachFile(file); 

        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(attachmentBodyPart);

        message.setContent(multipart);
        //send Email
        Transport.send(message);
        LOGGER.info("########################### Send email with attachement to " + destination + " End ########################### ");
    } catch (MessagingException e) {
        LOGGER.error("Error when send email to " + destination);
        throw new RuntimeException(e);
    }

我已经做了很多事情,我可能会厌倦找到错误xD

感谢您的帮助!!

更新:感谢jmehrens,我发现了这个问题。我的邮件服务器不允许.zip

1 个答案:

答案 0 :(得分:0)

确保您的邮件服务器没有适当的策略阻止传递扩展名为.zip的电子邮件。您应该只使用邮件客户端(或JavaMail)对其进行测试,并将扩展名重命名为.txt甚至.piz

阅读JavaMail FAQ。它充满了关于最佳实践,调试和故障排除步骤的良好信息。