Ao receber um e-mail em uma determinada conta. Preciso que envie esta informação a um sistema

Ao receber um e-mail em uma determinada conta. Preciso que envie esta informação a um sistema.

API em JAVA spring.

Qual framework preciso utilizar ?

1 curtida

Você esta procurando por um cliente de emails em java?

1 curtida

Tentou preencher “mail” nas dependências do Spring Initializr, só para ver o que poderia aparecer? Tenta lá.

2 curtidas


https://www.baeldung.com/spring-email
Infelizmente não encontrei meio de usar para verificar uma caixa de email, somente encontrei envio de email.
Kkk fui ate lá verificar, para vcs kk

1 curtida

Não é enviar e-mails com Spring.

exemplo:

Todo e-mail que chegar para o endereço suporte@teste.com.br, abrir um chamado no sistema.

uma possível solução pra isso seria usar o Scheduler do Spring para ficar acessando o email a cada X minutos, e caso encontre algo ele abra o chamado.
Não fica “tempo real” mas deve ser o suficiente pra resolver o caso.

1 curtida

Conecta no email usando o protocolo IMAP e você pode manipulá-los em tempo real com seu sistema.

1 curtida

Estou fazendo assim:

MailImapConfiguration

package br.com.ghnetsoft.gsssolucoes.email.config;

import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.mail.ImapMailReceiver;
import org.springframework.integration.mail.MailReceiver;
import org.springframework.integration.mail.MailReceivingMessageSource;
import org.springframework.messaging.Message;

import br.com.ghnetsoft.gsssolucoes.email.service.ReceiveMailService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableIntegration
public class MailImapConfiguration {

    @Autowired
    private ReceiveMailService receiveMailService;

    @ServiceActivator(inputChannel = "receiveEmailChannel")
    public void receive(final Message<?> message) {
        receiveMailService.handleReceivedMail((MimeMessage) message.getPayload());
    }

    @Bean("receiveEmailChannel")
    DirectChannel defaultChannel() {
        final DirectChannel directChannel = new DirectChannel();
        directChannel.setDatatypes(javax.mail.internet.MimeMessage.class);
        return directChannel;
    }

    @Bean()
    @InboundChannelAdapter(channel = "receiveEmailChannel", poller = @Poller(fixedDelay = "5000", taskExecutor = "apiEmailExecutor-"))
    MailReceivingMessageSource mailMessageSource(final MailReceiver mailReceiver) {
        final MailReceivingMessageSource mailReceivingMessageSource = new MailReceivingMessageSource(mailReceiver);
        return mailReceivingMessageSource;
    }

    @Bean
    MailReceiver imapMailReceiver(@Value("imaps://${mail.imap.username}:${mail.imap.password}@${mail.imap.host}:${mail.imap.port}/inbox") final String storeUrl) {
        log.info("IMAP connection url: {}", storeUrl);
        final ImapMailReceiver imapMailReceiver = new ImapMailReceiver(storeUrl);
        imapMailReceiver.setShouldMarkMessagesAsRead(true);
        imapMailReceiver.setShouldDeleteMessages(false);
        imapMailReceiver.setMaxFetchSize(10);
        // imapMailReceiver.setAutoCloseFolder(true);
        final Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        javaMailProperties.put("mail.imap.socketFactory.fallback", false);
        javaMailProperties.put("mail.store.protocol", "imaps");
        javaMailProperties.put("mail.debug", true);
        imapMailReceiver.setJavaMailProperties(javaMailProperties);
        return imapMailReceiver;
    }
}

ImapMailService

package br.com.ghnetsoft.gsssolucoes.email.service;

import javax.mail.internet.MimeMessage;

public interface ImapMailService {

    void handleReceivedMail(MimeMessage message);
}

ImapMailServiceImpl

package br.com.ghnetsoft.gsssolucoes.email.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.util.MimeMessageParser;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;

import br.com.ghnetsoft.gsssolucoes.email.service.ImapMailService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ImapMailServiceImpl implements ImapMailService {

    private static final String DOWNLOAD_FOLDER = "data";
    private static final String DOWNLOADED_MAIL_FOLDER = "DOWNLOADED";

    @Override
    public void handleReceivedMail(final MimeMessage receivedMessage) {
        try {
            final Folder folder = receivedMessage.getFolder();
            folder.open(Folder.READ_WRITE);
            final Message[] messages = folder.getMessages();
            fetchMessagesInFolder(folder, messages);
            Arrays.asList(messages).stream().filter(message -> {
                final MimeMessage currentMessage = (MimeMessage) message;
                try {
                    return currentMessage.getMessageID().equalsIgnoreCase(receivedMessage.getMessageID());
                } catch (final MessagingException e) {
                    log.error(e.getMessage(), e);
                    return false;
                }
            }).forEach(this::extractMail);
            copyMailToDownloadedFolder(receivedMessage, folder);
            folder.close(true);
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private void fetchMessagesInFolder(final Folder folder, final Message[] messages) throws MessagingException {
        final FetchProfile contentsProfile = new FetchProfile();
        contentsProfile.add(FetchProfile.Item.ENVELOPE);
        contentsProfile.add(FetchProfile.Item.CONTENT_INFO);
        contentsProfile.add(FetchProfile.Item.FLAGS);
        contentsProfile.add(FetchProfile.Item.SIZE);
        folder.fetch(messages, contentsProfile);
    }

    private void copyMailToDownloadedFolder(final MimeMessage mimeMessage, final Folder folder) throws MessagingException {
        final Store store = folder.getStore();
        final Folder downloadedMailFolder = store.getFolder(DOWNLOADED_MAIL_FOLDER);
        if (downloadedMailFolder.exists()) {
            downloadedMailFolder.open(Folder.READ_WRITE);
            downloadedMailFolder.appendMessages(new MimeMessage[]{ mimeMessage });
            downloadedMailFolder.close();
        }
    }

    private void extractMail(final Message message) {
        try {
            final MimeMessage messageToExtract = (MimeMessage) message;
            final MimeMessageParser mimeMessageParser = new MimeMessageParser(messageToExtract).parse();
            showMailContent(mimeMessageParser);
            downloadAttachmentFiles(mimeMessageParser);
            messageToExtract.setFlag(Flags.Flag.DELETED, true);
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private void showMailContent(final MimeMessageParser mimeMessageParser) throws Exception {
        log.debug("De: {} para: {} | Assunto: {}", mimeMessageParser.getFrom(), mimeMessageParser.getTo(), mimeMessageParser.getSubject());
        log.debug("Texto: {}", mimeMessageParser.getPlainContent());
    }

    private void downloadAttachmentFiles(final MimeMessageParser mimeMessageParser) {
        mimeMessageParser.getAttachmentList().forEach(dataSource -> {
            if (StringUtils.isNotBlank(dataSource.getName())) {
                final String rootDirectoryPath = new FileSystemResource("").getFile().getAbsolutePath();
                final String dataFolderPath = rootDirectoryPath + File.separator + DOWNLOAD_FOLDER;
                createDirectoryIfNotExists(dataFolderPath);
                final String downloadedAttachmentFilePath = rootDirectoryPath + File.separator + DOWNLOAD_FOLDER + File.separator + dataSource.getName();
                final File downloadedAttachmentFile = new File(downloadedAttachmentFilePath);
                try (OutputStream out = new FileOutputStream(downloadedAttachmentFile)) {
                    final InputStream in = dataSource.getInputStream();
                    IOUtils.copy(in, out);
                } catch (final IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }

    private void createDirectoryIfNotExists(final String directoryPath) {
        if (!Files.exists(Paths.get(directoryPath))) {
            try {
                Files.createDirectories(Paths.get(directoryPath));
            } catch (final IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

Só que ao iniciar mostra o erro

2024-12-24 09:05:23 - o.s.i.handler.LoggingHandler - org.springframework.messaging.MessagingException: failure occurred while polling for mail; nested exception is javax.mail.NoSuchProviderException: imaps

at org.springframework.integration.mail.MailReceivingMessageSource.doReceive(MailReceivingMessageSource.java:74)

at org.springframework.integration.endpoint.AbstractMessageSource.receive(AbstractMessageSource.java:184)

at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:212)

at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:407)

at org.springframework.integration.endpoint.AbstractPollingEndpoint.pollForMessage(AbstractPollingEndpoint.java:376)

at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$null$3(AbstractPollingEndpoint.java:323)

at org.springframework.integration.util.ErrorHandlingTaskExecutor.lambda$execute$0(ErrorHandlingTaskExecutor.java:57)

at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)

at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)

at java.base/java.lang.Thread.run(Thread.java:840)

Caused by: javax.mail.NoSuchProviderException: imaps

at javax.mail.Session.getService(Session.java:856)

at javax.mail.Session.getStore(Session.java:626)

at javax.mail.Session.getStore(Session.java:589)

at org.springframework.integration.mail.AbstractMailReceiver.connectStoreIfNecessary(AbstractMailReceiver.java:319)

at org.springframework.integration.mail.AbstractMailReceiver.openFolder(AbstractMailReceiver.java:339)

at org.springframework.integration.mail.AbstractMailReceiver.receive(AbstractMailReceiver.java:371)

at org.springframework.integration.mail.MailReceivingMessageSource.doReceive(MailReceivingMessageSource.java:60)

... 9 more

O que pode ser ?