【问题标题】:Converting Java sendEmail method to Groovy将 Java sendEmail 方法转换为 Groovy
【发布时间】:2017-11-13 20:32:15
【问题描述】:

我有一个通过电子邮件发送文件附件的 Java 方法。我正在尝试将它作为 Grails 应用程序的一部分移植到 Groovy。我对FileDataSource 声明的格式有疑问。违规代码标有星号。在 Groovy 中执行该部分的正确方法是什么?我似乎在网上找不到任何东西。

public static void sendEmail(String sendFile)
    {
    //
    // Send the log file via email.
    //
    final String username = "myname@mydomain.com"
    final String password = "mypassword"

    // Strings that contain from, to, subject, body and file path to the attachment
    String from = username;
    String subject = "Test Results"
    String body = "Body of Test Results email."
    String filename = sendFile

    // Set smtp properties
    Properties properties = new Properties()
    properties.put("mail.smtp.starttls.enable", "true")
    properties.put("mail.smtp.auth", "true")
    properties.put("mail.smtp.host", "smtp.gmail.com")
    properties.put("mail.smtp.port", "587")

    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username,password)
        }
    });

    try
    {
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(from))
        // For debug uncomment the line below and enter your email address.
        //message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("peter.cook@studentuniverse.com"));
        // For debug comment the line below out.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("cccm@studentuniverse.com,WebsiteOperations@studentuniverse.com,peter.cook@studentuniverse.com"))
        message.setSubject(subject)
        message.setSentDate(new Date())

        // Set the email body
        MimeBodyPart messagePart = new MimeBodyPart()
        messagePart.setText(body)

        // Set the email attachment file
        MimeBodyPart attachmentPart = new MimeBodyPart()
        *FileDataSource fileDataSource = new FileDataSource(filename)
        *{
        *    @Override
        *    public String getContentType()
        *    {
        *        return "application/octet-stream"
        *    }
        * }
        attachmentPart.setDataHandler(new DataHandler(fileDataSource))
        attachmentPart.setFileName(fileDataSource.getName())

        // Add all parts of the email to Multipart object
        Multipart multipart = new MimeMultipart()
        multipart.addBodyPart(messagePart)
        multipart.addBodyPart(attachmentPart)
        message.setContent(multipart)

        // Send email
        Transport.send(message)
        System.out.println("Mail sent!")
    }
    catch (MessagingException e)
    {
        e.printStackTrace()
    }
}

【问题讨论】:

  • 尝试将“{”与new FileDataSource(filename)放在同一行。

标签: grails groovy


【解决方案1】:

那种糟糕的大括号样式与不需要分号的 Groovy 相冲突。不需要非匿名类定义,除非它会被多次使用,只需像这样声明它:

FileDataSource fileDataSource = new FileDataSource(filename) {
    String getContentType() { 'application/octet-stream' }
}

【讨论】:

  • 啊,比我的+1好。我知道有一种更简洁的方法,只是不想弄乱语法。
【解决方案2】:

通过将compile 'org.grails.plugins:mail' 添加到您的build.gradle 来安装mail 插件,然后阅读文档here

如果您在安装时遇到问题,请尝试compile 'org.grails.plugins:mail:2.0.0.RC1'

然后,对于smtp configuration,您需要将其迁移到配置文件:

如果你完成了,你应该可以在上面的 sn-p 之后发送一封电子邮件:

mailService.sendMail {
   to "fred@gmail.com","ginger@gmail.com"
   from "john@gmail.com"
   cc "marge@gmail.com", "ed@gmail.com"
   bcc "joe@gmail.com"
   subject "Hello John"
   text 'this is some text'
}

【讨论】:

    【解决方案3】:

    您指出的代码是一个覆盖单个方法 (getContentType) 的匿名内部类,而 groovy 可能在处理它时遇到了一些麻烦,因为它看起来像一个“新对象”,后面有一个闭包。

    如果您想坚持 java 风格的外观,我建议您将其从匿名内部类更改为单独的类。在此类中的其他代码之外的类似内容(如果它不是公共类,它可以在同一个文件中):

        class ForceOctetStreamFileDataSource extends FileDataSource
        {
            public ForceOctetStreamFileDataSource(String filename) {
                super(filename);
            }
    
            @Override
            public String getContentType()
            {
                return "application/octet-stream"
            }
        }
    

    然后在你的类中用 new ForceOctetStreamFileDataSource(filename) 替换它

    这应该足够明确,以免混淆 groovy。可能有一种更短的“Groovy”方式涉及我现在不想猜测的闭包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 2012-09-18
      • 2011-09-21
      相关资源
      最近更新 更多