繁体   English   中英

在groovy中发送邮件

[英]sending mail in groovy

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

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()
    }
}
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(attachment)始终尝试访问该文件,因此,如果您不提供任何附件或任何无效文件作为附件,则它将尝试访问不可用的文件并抛出IOException。

如果不附加任何内容,为什么不简单不附加?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM