K
K
KateM932018-10-01 17:20:17
Java
KateM93, 2018-10-01 17:20:17

Problem with protocols or something else?

I need to connect with the slek, pull out all the messages from the channels and create folders with the names of these channels in the mail and forward the messages to these folders.
I used simple-slack-api, jslack, javamail.
I have "sentMessage" method to create folders with "chan" headers, but getMessage() method doesn't work for me
If

for (String chan : channels){
sentMessage(chan);//change where to insert
System.out.println(chan);

sentMessage(chan) works, but the getMessage() method throws an error every time a message is sent:
"Something went wrong javax.mail.MessagingException: Could not to SMTP host: localhost, port 25; nested exception is : java.net. Connection refused connect"
When I comment the sentMessage(chan);
I only receive messages.
How to combine all this to make it work?
My java code.
spoiler
package ru.slacks;
        import com.github.seratch.jslack.*;
        import com.github.seratch.jslack.api.methods.SlackApiException;
        import com.github.seratch.jslack.api.methods.request.channels.ChannelsListRequest;
        import java.io.IOException;
        import java.util.List;
        import java.util.Properties;
        import java.util.Scanner;
        import com.github.seratch.jslack.api.methods.request.im.ImListRequest;
        import com.ullink.slack.simpleslackapi.*;
        import com.ullink.slack.simpleslackapi.SlackSession;
        import com.ullink.slack.simpleslackapi.events.SlackMessagePosted; 
        import com.ullink.slack.simpleslackapi.impl.ChannelHistoryModuleFactory;
        import static java.util.stream.Collectors.toList;
        import com.ullink.slack.simpleslackapi.impl.SlackSessionFactory;
        import org.glassfish.grizzly.http.server.util.StringParser;
        import javax.mail.*;
        import javax.mail.internet.InternetAddress;
        import javax.mail.internet.MimeMessage;
        import javax.swing.*;

        public class SlackTools {
            public SlackTools() throws IOException, SlackApiException {        
            }

         private String token=".....our_token......";
            static final Slack slack = Slack.getInstance();


            List<String> channels = slack.methods().channelsList(ChannelsListRequest.builder().token(token).build())
                    .getChannels().stream().map(c -> c.getId()).collect(toList());
        public void getChannels() throws IOException, SlackApiException {
                System.out.println("---------------Channels---------------");

                for (String chan : channels){
                sentMessage(chan);//поменять куда вставить
                System.out.println(chan);

            }
    }

      public class EmailAuthenticator extends javax.mail.Authenticator
        {
            private String login;
            private String password;
            public EmailAuthenticator (final String login, final String password)
            {
                this.login = login;
                this.password = password;
            }
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(login, password);
            }
        }

  public void sentMessage(String chanel) throws IOException  {

    Properties imap = new Properties();
        imap.put("mail.debug"          , "false"  );
        imap.put("mail.store.protocol" , "imaps"  );//для доступа и обработки сообщений
        imap.put("mail.imap.ssl.enable", true);
        imap.put("mail.imap.port", 993);
    Authenticator auth = new EmailAuthenticator("[email protected]",
            "test123456");

        Session session = Session.getDefaultInstance(imap, auth);
        session.setDebug(false);
        try {
            Store store = session.getStore();

            // Подключение к почтовому серверу
            store.connect("imap.yandex.ru", "[email protected]", "test123456");

            // Папка входящих сообщений
            Folder inbox = store.getFolder(chanel);
            if (!inbox.exists())
                if (inbox.create(Folder.HOLDS_MESSAGES))
                    System.out.println("Folder was created successfully");
            // Открываем папку в режиме только для чтения
            //inbox.open(Folder.READ_ONLY);
            inbox.open(Folder.READ_WRITE);
            System.out.println("Количество сообщений : " +
                    String.valueOf(inbox.getMessageCount()));

            if (inbox.getMessageCount() == 0)
                return;


        } catch (NoSuchProviderException e) {
            System.err.println(e.getMessage());
        } catch (MessagingException e) {
            System.err.println(e.getMessage());
        }
    }





        public void getMessage() throws IOException  {


            Properties p = new Properties();
            p.put("mail.smtp.host", "smtp.yandex.ru");//протокол передачи сообщений, или smtp.gmail.com
            p.put("mail.smtp.socketFactory.port", 465);
            p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            p.put("mail.smtp.auth", true);
            p.put("mail.smtp.port", 465);
           // p.put("mail.transport.protocol", "smtp");
            Scanner in = new Scanner(System.in);
            System.out.print("Enter your e-mail ");
            String user = in.nextLine();
            System.out.println("Enter your  password");
            String password = in.nextLine();

            Session s = Session.getDefaultInstance(p,
                    new Authenticator(){
                        protected PasswordAuthentication getPasswordAuthentication(){
                            return new PasswordAuthentication(user, password);}});

            System.out.print("Enter usernameto ");
            String userto = in.nextLine();

            for(String chan : channels ){

                SlackSession sessiont = SlackSessionFactory.createWebSocketSlackSession(token);
                sessiont.connect(); 
                ChannelHistoryModule channelHistoryModule = ChannelHistoryModuleFactory.createChannelHistoryModule(sessiont);
                List<SlackMessagePosted> messages = channelHistoryModule.fetchHistoryOfChannel(chan).stream().collect(toList());







                System.out.println("---------------Messages- " + chan + "--------------");

                for (SlackMessagePosted message : messages) {
                    System.out.println("E-mail:" + message.getUser().getUserMail() +  ", message: " + message.getMessageContent() );
                    try {
                        Message mess = new MimeMessage(s);


                        mess.setFrom(new InternetAddress(user));

                        mess.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userto));

                        mess.setSubject(message.getMessageContent().toString());
                        mess.setText(chan);
                        Transport.send(mess);
                                    JOptionPane.showMessageDialog(null, "Письмо отправлено" );

                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Что то пошло не так" + ex);
                    }

                }
            }
        }

        public static void main(String[] args) throws IOException, SlackApiException, MessagingException {
      SlackTools sl = new SlackTools();

           sl.getChannels();
           sl.getMessage();
            System.exit(0);

        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nur-Magomed, 2018-10-29
@efive

It looks like you still have localhost as the host in the parameters, of course, he tries to connect there and gets "connection refused".
Try instead: Call PS Are you sure the error is in the getMessage method? I didn’t see that host/port was specified in your sentMessage() method :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question