【问题标题】:Attaching a file in Grails using Mail plugin使用 Mail 插件在 Grails 中附加文件
【发布时间】:2010-02-19 09:30:27
【问题描述】:

我用的是mail 0.9,好像还没有附件功能?这个item 到现在还没有被收录吗?

如果是这样,请告诉我如何在不直接破解代码的情况下扩展 Grails 插件。

谢谢。

【问题讨论】:

    标签: grails plugins email


    【解决方案1】:

    看来我错过了documentation 中的附件部分。我看到的是 TODO 部分(顺便说一句,应该更新)。无论如何,这里有一个比那里提到的更清晰的例子。

    String path = "./web-app/images/grails_logo.jpg"
    
    sendMail {
       multipart true
       to 'alfred@fbmsoftware.com'
       subject "Welcome to Grails!"
       body '''
           Greetings Earthlings!
       '''
       attachBytes path,'image/jpg', new File(path).readBytes()
    }
    

    有了这个,你可以附加任何类型的文件,只要你正确指定我猜的内容类型。

    【讨论】:

    • 正确,使用邮件 0.9,我已经能够按照您的说明获取附件。
    【解决方案2】:

    Grails 插件('grails install-plugin mail')即使在 TLS 上也能完美运行 - 请参阅 mac.com 发送要求。

    但是,对于那些使用 Outlook 或其他公司电子邮件系统的人,我发现使用 resources.xml 和 Spring JavaMail 帮助类的 Grails 解决方案略有不同:

    1) 将以下内容添加到 myapp/grails-app/conf/spring/resources.xml(见下文)

    2) 根据需要在业务服务中定义服务。

    3) 添加一些导入 - 完成! 导入 javax.mail.internet.MimeMessage 导入 org.springframework.core.io.FileSystemResource 导入 org.springframework.mail.javamail.MimeMessageHelper

    定义邮件发件人

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    
      <!-- Mail service -->
      <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="mail.munger.somecorp.com"/>
        <property name="port" value="25"/>
    
        <property name="javaMailProperties">
          <props>
            <prop key="mail.debug">false</prop>
          </props>
        </property>
      </bean>
    
      <!-- more bean definitions go here... -->
    
    </beans>
    

    添加附件的Java代码:

      MimeMessage message = mailSender.createMimeMessage()
      MimeMessageHelper helper = new MimeMessageHelper( message, true )
    
      for ( String recipients : [ customer1, customer2, customer3, customer4 ].findAll { it != null } )
      {
          helper.addTo( str );
      }
      helper.setFrom( "" )
      helper.setSubject( aSubject )
      helper.setText("...")
    
      FileSystemResource fileResource =
        new FileSystemResource( new File(tempFile) )
      helper.addAttachment( tempFile.substring(tempFile.lastIndexOf( "/" ) + 1), fileResource, "application/pdf" )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 2016-05-13
      • 2023-03-15
      • 2012-02-11
      相关资源
      最近更新 更多