将Java sendEmail方法转换为Groovy

时间:2017-11-13 20:32:15

标签: grails groovy

我有一种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()
    }
}

3 个答案:

答案 0 :(得分:1)

糟糕的支撑风格与不需要分号的Groovy相冲突。不需要非匿名类定义,除非它将被多次使用,只需声明如下:

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

答案 1 :(得分:0)

你指出的代码是一个重写单个方法(getContentType)的匿名内部类,而groovy可能在处理它时遇到一些麻烦,因为它看起来像一个"新对象"在它之后关闭。

如果你想坚持使用java-ish的话,我建议你把它从一个匿名的内部类改为一个单独的类。在这个类的其他代码之外的东西(如果它不是公共类,它可以在同一个文件中):

    class ForceOctetStreamFileDataSource extends FileDataSource
    {
        public ForceOctetStreamFileDataSource(String filename) {
            super(filename);
        }

        @Override
        public String getContentType()
        {
            return "application/octet-stream"
        }
    }

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

这应该足够明确,不要混淆常规。可能会有更短的时间" Groovy"涉及闭包的方式,我现在不想猜。

答案 2 :(得分:0)

通过向mail添加compile 'org.grails.plugins:mail'安装build.gradle插件,然后阅读doco here

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

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

如果你已经完成了,你应该可以在上面的代码段之后发送一封电子邮件:

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