首页 > 解决方案 > 如何使用 DataHandler 和 FileDataSource 在 apache camel 中发送带有附件和文件大小验证的邮件

问题描述

在 apache camel 中向带有附件的收件人发送邮件时出错注意:ajay.jpeg 存在于图像文件夹的 src/main/resources 中,绝对路径有效,但相对路径失败。

@Override
public void process(Exchange exchange) throws Exception {
   exchange.getIn().addAttachment("ajay.jpeg",
   new DataHandler(new FileDataSource("images/ajay.jpeg")));        
}

原因:java.io.FileNotFoundException: images\ajay.jpeg(系统找不到指定的路径)

标签: emailapache-camel

解决方案


Finally got the solution after multiple tries.

  private final DataSource ds = new URLDataSource(getClass().getClassLoader().getResource("images/ajay.jpeg"));    
        @Override
        public void process(Exchange exchange) throws Exception {           
            try
            {           
                Message in = exchange.getIn();
                in.addAttachment("ajay.jpeg",new DataHandler(ds));  
                if(in.getBody()!=null) {
                    String payload=in.getBody(String.class);    

                    if((payload.length()) <= (1048576)) {
                    in.addAttachment("data.txt", new DataHandler(payload,"text/html"));
                    }else {
                        log.info("file size is More  than 1 mb");   

                    }
                }

            }catch(Exception e) {
                log.error("exception occured in processing the mail cause : msg {}",e.getCause(),e.getMessage());
            }   

        }

推荐阅读