【问题标题】:Mail plugin in GrailsGrails 中的邮件插件
【发布时间】:2016-05-25 16:24:18
【问题描述】:

我正在尝试通过我的 grails 应用程序发送邮件。我正在使用this 插件。我已经把它放在build.gradle 中,如下所示:

compile "org.grails.plugins:mail:1.0.7"

并刷新了项目。在那之后,我启动了 Grails (v3) 并做了run-app。当我尝试运行 sendMail 时,我得到了这个异常:

这是我的电话,emailmessageString 类型的变量:

sendMail {
    to email
    subject "Contact"
    body message
}

在插件文档中,它说:

邮件插件提供了可以在 Grails 应用程序中的任何位置使用的 MailService。 MailService 提供了一个名为 sendMail 的方法,该方法接受一个闭包。此外,将 sendMail 方法注入到所有控制器中以简化访问。

我从未进行过依赖注入(不需要),但我尝试声明def mailService,然后调用mailService.sendMail,但在mailService 上得到了NullPointerException

我认为这不重要,但我没有安装/运行邮件服务器,但我怀疑这会导致找不到方法错误。

我可以确认 IntelliJ IDEA 的 Gradle 视图中显示了正确的依赖项,因此它可以正确安装。

【问题讨论】:

  • 如果你做 Grails,你就做依赖注入。
  • 如果运行:grails install-plugin mail 会发生什么
  • @pczeus "$ grails install-plugin mail | 找不到错误命令 install-plugin 您的意思是:安装或列出插件或插件信息?"
  • 这看起来不像 Grails 3 的 Mail 插件的正确版本。它应该是 2.0.0.RC4 版本,请参见此处:bintray.com/grails/plugins/mail/view
  • 我是直接从邮件插件网站拿的:grails.org/plugin/mail

标签: grails gradle dependency-injection


【解决方案1】:

您使用的 Mail 插件版本与 Grails 3 不兼容。如果您想使用该插件,请访问以下网址:

https://bintray.com/grails/plugins/mail/view

选择您想要的版本。所有与 Grails 3 兼容的插件都在 https://bintray.com/grails/plugins 中,而不是来自 grails.org 的最旧 url

使用示例:

import grails.plugins.mail.MailService

@Transactional
class SendMailService {

    MailService mailService

    def sendMail(email, subjectMail, bodyMail) {
        mailService.sendMail {
             to email
             subject subjectMail
             html bodyMail
        }
    }
}

【讨论】:

    【解决方案2】:

    既然我知道这应该可行,我会假设当你说你“尝试使用 def mailService”时,你这样做是在错误的地方。

    如果您执行以下操作,您的控制器应该可以工作:

    class ContactController {
        def mailService   // note it must be outside of any methods/closure
    
        def someAction() {
            String email = "bob@gmail.com"
            String message = "This is the email text"
            // some code here is fine
            mailService.sendMail {
                to email
                subject "Contact"
                body message
            }
           // more code here is fine
       }
    }
    

    查看注入的服务必须如何命名为“mailService”,并且必须存在于任何闭包或操作之外。 Grails 将查找任何名为 MailService 的类,将其实例化并注入,自动将变量 mailService 设置为对服务的引用。

    这一切都假定您为您使用的任何版本的 Grails 提供了正确的服务

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多