在groovy发送邮件

时间:2015-12-08 08:49:22

标签: java email groovy

我在我的程序中编写了这段代码,当我在附件中传递文件路径时,它成功发送邮件(例如:attachment =" / home / Aman / file .txt")*但是当我不必附加任何文件时发送邮件时会抛出 IOException。*我试过在 messageBodyPart.attachFile之前应用条件(附件)但它也抛出相同的异常。

def sendMail(String message, String attachment, String subject) {
    Properties properties = System.getProperties()
    properties.setProperty("mail.smtp.host", eMailSMTPHost)
    properties.setProperty("mail.smtp.port", eMailSMTPIPPort)
    Session session = Session.getDefaultInstance(properties)
    try{
        // Create a default MimeMessage object.
        MimeMessage msg = new MimeMessage(session)
        msg.setFrom(new InternetAddress(eMailSendFrom))
        eMailSendTo.split(',').each(){ item ->      msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress(item)    )
        }
        eMailSendCc.split(',').each(){ item -> msg.addRecipient(Message.RecipientType.CC,
            new InternetAddress(item)    )
        }
        msg.setSubject(subject)
        BodyPart messageBodyPart = new MimeBodyPart()
        messageBodyPart.setContent(message,"text/html")
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messageBodyPart)

        messageBodyPart = new MimeBodyPart()
        messageBodyPart.attachFile(attachment)  
        multipart.addBodyPart(messageBodyPart)

        // Send the complete message parts
        msg.setContent(multipart)
        Transport.send(msg)     
        System.exit(0)
    } catch(RuntimeException e) {
        println e.getMessage()
    }
}

2 个答案:

答案 0 :(得分:2)

if(!attachment.equals("") && !attachment.isEmpty()) {
        BodyPart messageBodyPart = new MimeBodyPart()
        messageBodyPart.setContent(message,"text/html")
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messageBodyPart)

        messageBodyPart = new MimeBodyPart()
        messageBodyPart.attachFile(attachment)
        multipart.addBodyPart(messageBodyPart)              
        // Send the complete message parts
        msg.setContent(multipart)
    } 
    else {
        msg.setContent(message, "text/html")
    }

在代码段中进行上述更改。它会工作 由于 messageBodyPart.attachFile(附件)总是尝试访问该文件,因此,如果您不提供任何附件或任何无效文件作为附件,那么它将尝试访问不可用的文件并抛出IOException异常。

答案 1 :(得分:1)

如果没有什么可附加的话,为什么不简单地附上?

if(attachment != null){
 messageBodyPart = new MimeBodyPart()
 messageBodyPart.attachFile(attachment)
 multipart.addBodyPart(messageBodyPart)
}