I have written this snippet of code in my program and it is successfully sending mail when I am passing file path in the attachment(Ex:attachment = "/home/Aman/file.txt")* but it is throwing IOException while sending mail when I don't have to attach any file.* I have tried by applying condition before messageBodyPart.attachFile(attachment) but it is also throwing same exception.
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")
    }
Do the above changes in the snippet of code. It'll work.
As messageBodyPart.attachFile(attachment) always try to access the file so, if you will not give any attachment or any invalid file as attachment then it will try to access the file which is not available and throw the IOException.
Why not simply don't attach if there is nothing to attach?
if(attachment != null){
 messageBodyPart = new MimeBodyPart()
 messageBodyPart.attachFile(attachment)
 multipart.addBodyPart(messageBodyPart)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With