如何通过camel spring DSL发送文件作为邮件附件

Cza*_*zar 3 java spring apache-camel

我在我们当前的项目中使用Camel 2.9.x进行集成.其中一个路由由两个端点组成 - 文件轮询端点和smtp邮件端点.必须通过smtp端点作为附件发送第一个端点生成的文件.

对于Camel配置,我们使用Spring DSL(这实际上是一个要求).Spring版本是3.1.1.不幸的是,我发现只有java dsl示例和将文件附加到camel路由中的电子邮件的文档.

<endpoint uri="file:///path/to" id="file-source"/>
<endpoint uri="smtp://mail.example.com:25/?username=someuser@example.com&amp;password=secret&amp;to=recv@example.com" id="mail-dest"/>
<route id="simplified-for-readability">
  <from ref="file-source"/>
  <to ref="mail-dest"/>
</route>
Run Code Online (Sandbox Code Playgroud)

此配置将文件作为普通/文本正文发送,而不是作为附件(甚至二进制文件)发送.有没有办法在不使用Java dsl的情况下将文件作为附件发送?

Pet*_*der 11

这可以通过Spring配置来完成,但是你可能需要编写一个简单的java bean代码,尽管这与spring或java DSL没有关系.

首先创建一个类似于这个的类(你可能需要修复这里的东西):

// Note: Content Type - might need treatment!
public class AttachmentAttacher{
   public void process(Exchange exchange){
      Message in = exchange.getIn();
      byte[] file = in.getBody(byte[].class);
      String fileId = in.getHeader("CamelFileName",String.class);
      in.addAttachment(fileId, new DataHandler(file,"plain/text"));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需连接一个弹簧豆并在你的路线中使用它.应该做的伎俩.

<bean id="attacher" class="foo.bar.AttachmentAttacher"/>

<route>
  <from ref="file-source"/>
  <bean ref="attacher"/>
  <to ref="mail-dest"/>
</route>
Run Code Online (Sandbox Code Playgroud)


小智 5

这对我有用,上面的内容略有不同。

import javax.activation.DataHandler;
import javax.mail.util.ByteArrayDataSource;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;

public class AttachmentAttacher implements Processor {

  private final String mimetype;

  public AttachmentAttacher(String mimetype) {
    this.mimetype = mimetype;
  }

  @Override
  public void process(Exchange exchange){
    Message in = exchange.getIn();
    byte[] file = in.getBody(byte[].class);
    String fileId = in.getHeader("CamelFileName",String.class);
    in.addAttachment(fileId, new DataHandler(new     ByteArrayDataSource(file, mimetype)));
  }
}
Run Code Online (Sandbox Code Playgroud)