关于发送电子邮件的groovy.lang.GroovyRuntimeException

时间:2014-10-01 22:12:02

标签: email groovy apache-commons-net

我正在尝试从groovy脚本发送电子邮件。我已经给出了以下代码:

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')

我正在使用apache的commons-net-2.0.jar来运行代码。错误消息如下:

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)

错误似乎来自代码的这一部分:

writer = new PrintWriter(client.sendMessageData())

我尝试打印出client.sendMessageData(),值为null。理想情况下,它应该是表示Writer对象的一些值。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:4)

问题如下:

new PrintWriter(client.sendMessageData())

我认为如果命令由于某种原因失败,sendMessageData将返回null。当您将null传递给PrintWriter构造函数时,Groovy的动态调度机制无法知道您尝试调用哪个构造函数。你可以这样做:

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

这将消除模糊方法重载问题,但仍可能不是你想要的。您可能希望在实例化PrintWriter之前检查null的返回值。