Search code examples
emailgroovyapache-commons-net

groovy.lang.GroovyRuntimeException on sending an Email


I am trying to send an email from a groovy script. I have given the code below:

import org.apache.commons.net.smtp.*

port = 25
org = 'mycompany.org'


client = new SMTPClient()
client.connect('<server_name>', port)
client.login()

// set sender and recipient
client.sender = "<email_address>"
client.addRecipient("<email_address>")

// create and send header information
header = new SimpleSMTPHeader("<email_address>",
        "<email_address>", 'Successful build')
header.addCC("<email_address>")
header.addHeaderField('Organization', org)
writer = new PrintWriter(client.sendMessageData())
writer << header

// send body of message
writer << 'Successful build for ' + new Date()
writer.close()

client.logout()
client.disconnect()

fixture.assertEmailArrived(from: "cruise@$org",
                           subject: 'Successful build')

I am using the apache's commons-net-2.0.jar to run the code. The error message is as below:

Caught: groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.io.PrintWriter#<init>.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [class java.lang.String]
    [class java.io.File]
    [class java.io.Writer]
    [class java.io.OutputStream]
groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.io.PrintWriter#<init>.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [class java.lang.String]
    [class java.io.File]
    [class java.io.Writer]
    [class java.io.OutputStream]
    at TestEmail.run(TestEmail.groovy:20)

The error seems to come from this part of the code:

writer = new PrintWriter(client.sendMessageData())

I tried to print out the client.sendMessageData() and the value is coming out as null. It should ideally have been some value denoting a Writer object. Please help me resolve the issue.


Solution

  • The problem is the following:

    new PrintWriter(client.sendMessageData())
    

    I think sendMessageData returns null if the command fails for some reason. When you pass null to the PrintWriter constructor, Groovy's dynamic dispatch mechanism does not have any way to know which constructor you are trying to call. You could do this:

    new PrintWriter((Writer)client.sendMessageData())
    

    That will do away with the ambiguous method overloading issue, but still probably isn't what you want. You probably want to check the return value for null before instantiating the PrintWriter to begin with.