【问题标题】:how to create imap receiver adapter dynamically using spring boot?如何使用spring boot动态创建imap接收器适配器?
【发布时间】:2017-07-06 22:12:18
【问题描述】:

如何创建直接通道、imap 通道适配器并传递用户帐户信息,以便程序开始寻找新邮件。

我已经使用 xml 配置实现了邮件接收器。

<?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.xsd
    http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
    http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
   xmlns:int="http://www.springframework.org/schema/integration"
   xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
   xmlns:util="http://www.springframework.org/schema/util">

<int:channel id="emails"/>

<util:properties id="javaMailProperties">
    <prop key="mail.imap.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
    <prop key="mail.imap.socketFactory.fallback">false</prop>
    <prop key="mail.store.protocol">imaps</prop>
    <prop key="mail.debug">true</prop>
</util:properties>

<int-mail:imap-idle-channel-adapter id="mailAdapter"
                              store-uri="imaps://login:pass@imap-server:993/INBOX"
                              java-mail-properties="javaMailProperties"
                              channel="emails"
                              should-delete-messages="false"
                              should-mark-messages-as-read="true">
</int-mail:imap-idle-channel-adapter>

下面是使用xml文件的Java文件。

public class EmailIntegrationTesting {

private static Logger logger = LoggerFactory.getLogger(EmailIntegrationTesting.class);

public static void main(String[] args) throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext("gmail-imap.xml");

    DirectChannel inputChannel = ac.getBean("receiveChannel", DirectChannel.class);
    inputChannel.subscribe(new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {


            MailToStringTransformer m2s = new MailToStringTransformer();
            m2s.setCharset("utf-8");
            System.out.println("Message: " + m2s.transform(message));

            System.out.println("Message: " + message.getPayload());
            Object payload = message.getPayload();

            if (payload instanceof MimeMessage) {
                try {

                    javax.mail.Message mailMessage = (javax.mail.Message) payload;
                    System.out.println(mailMessage.getSubject());
                    System.out.println(getTextFromMessage(mailMessage));

                    Address[] receipts = mailMessage.getAllRecipients();
                    System.out.println("RECEIPIENTS MAIL ID");
                    if (receipts != null && receipts.length > 0) {
                        for (int i = 0; i < receipts.length; i++) {
                            System.out.println(((InternetAddress) receipts[i]).getAddress());
                        }
                    }

                    System.out.println("FROM MAIL ID");
                    Address[] froms = mailMessage.getFrom();
                    String email = froms == null ? null
                            : ((InternetAddress) froms[0]).getAddress();
                    System.out.println(email);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    });
}

private static String getTextFromMessage(javax.mail.Message message) throws Exception {
    String result = "";
    if (message.isMimeType("text/plain")) {
        result = message.getContent().toString();
    } else if (message.isMimeType("multipart/*")) {
        MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
        result = getTextFromMimeMultipart(mimeMultipart);
    }
    return result;
}

private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws Exception {
    String result = "";
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result = result + "\n" + bodyPart.getContent();
            break; // without break same text appears twice in my tests
        } else if (bodyPart.isMimeType("text/html")) {
            String html = (String) bodyPart.getContent();
            // result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result = result + getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
        }
    }
    return result;
}

}

我可以使用上面的代码成功接收邮件。

我还可以将 xml 转换为 java config。下面是代码。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mail.ImapIdleChannelAdapter;
import org.springframework.integration.mail.ImapMailReceiver;
import java.util.Properties;

@Configuration
class ImapConfiguration {

private Properties javaMailProperties() {
    Properties javaMailProperties = new Properties();

    javaMailProperties.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    javaMailProperties.setProperty("mail.imap.socketFactory.fallback","false");
    javaMailProperties.setProperty("mail.store.protocol","imaps");
    javaMailProperties.setProperty("mail.debug","true");

    return javaMailProperties;
}

@Bean
ImapIdleChannelAdapter mailAdapter() {
    ImapMailReceiver mailReceiver = new ImapMailReceiver("imaps://login:pass@imap-server:993/INBOX");

    mailReceiver.setJavaMailProperties(javaMailProperties());
    mailReceiver.setShouldDeleteMessages(false);
    mailReceiver.setShouldMarkMessagesAsRead(true);

    return new ImapIdleChannelAdapter(mailReceiver);
}

@Bean
public MessageChannel emails() {
 return new DirectChannel();
}

}

现在,我的意思是我想动态配置上面的代码。

USECASE 当用户填写 imap 服务器详细信息时,它应该开始查找传入的电子邮件。表示我不想在服务器启动时创建 bean。

【问题讨论】:

    标签: java spring spring-boot spring-integration spring-java-config


    【解决方案1】:

    请参阅 my answer to this questionits follow-up

    您还可以使用 Java DSL 来动态注册流...

    @Autowired
    private IntegrationFlowContext flowContext;
    
    ...
    
        IntegrationFlow flow = IntegrationFlows.from(Mail.imapIdleAdapter(...)
                                .handle(...)
                                ...
                                .get();
        IntegrationFlowRegistration flowRegistration =
                    this.flowContext.registration(flow)
                            .register();
    

    编辑

    添加了一个示例引导应用程序

    @SpringBootApplication
    public class So42297006Application {
    
        public static void main(String[] args) throws Exception {
            ConfigurableApplicationContext context = SpringApplication.run(So42297006Application.class, args);
            context.getBean(So42297006Application.class).runDemo();
            context.close();
            System.exit(0);
        }
    
        public void runDemo() throws Exception {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter username");
            String user = scanner.next();
            System.out.println("Enter pw");
            String pw = scanner.next();
            scanner.close();
            startMail(user, pw);
            Thread.sleep(10_000);
        }
    
        @Autowired
        private IntegrationFlowContext flowContext;
    
        public void startMail(String user, String pw) {
            IntegrationFlow flow = IntegrationFlows
                    .from(Mail.imapIdleAdapter(imapUrl(user, pw))
                            .javaMailProperties(p -> p.put("mail.debug", "false"))
                            .userFlag("testSIUserFlag") // needed by the SI test server - not needed if server supports /SEEN
                            .headerMapper(new DefaultMailHeaderMapper()))
                    .handle(System.out::println)
                    .get();
            this.flowContext.registration(flow).register();
        }
    
        private String imapUrl(String user, String pw) {
            return "imap://"
                    + user + ":" + pw
                    + "@localhost:" + imapServer().getPort() + "/INBOX";
        }
    
        @Bean
        public TestMailServer.ImapServer imapServer() {
            return TestMailServer.imap(0);
        }
    
    }
    

    Maven 部门:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mail</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-test</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-java-dsl</artifactId>
        </dependency>
    

    【讨论】:

    • 大家好,我是春天的新手,对applicationContext了解不多。但是是否可以创建在某些事件发生时开始接收邮件的频道。在我的情况下,用户需要填写 imap 配置,当他填写配置并单击保存按钮时,我需要即时启动 imap 接收器。可能吗?能否请您添加工作示例?
    • 我的答案中的示例将完全做到这一点 - 只要您注册流程,邮件适配器就会启动。
    • 我添加了一个简单的例子。
    • 非常感谢这个解决方案,它运行良好。不过我有一个问题,在“句柄”中实现的消息是一个 GenericMessage,而有效负载只是一个字符串,在 OP 帖子中,消息中的有效负载是一个 AbstractMailReceiver$IntegrationMimeMessage,我认为这更容易使用.你知道为什么吗?
    • 当答案是旧的(4 年以上)时,通常最好提出一个新问题,参考这个答案,而不是评论;事情可能已经改变了。这是因为我添加了一个标头映射器 - 请参阅 setHeaderMapper() 的 javadocs。 `* Set the header mapper; if a header mapper is not provided, the message payload is * a {@link MimeMessage}, when provided, the headers are mapped and the payload is * the {@link MimeMessage} content.
    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 2017-11-28
    • 2019-12-16
    • 2016-05-21
    • 2017-04-12
    • 2017-01-25
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多