Как исправить недопустимый протокол: пустая отправка почты и не удалось на узел SMTP: с помощью javax.mail? - PullRequest
0 голосов
/ 01 октября 2018

У меня проблема, я использую слабину и почту.

У меня есть метод для создания папки с заголовком "chan", но он не работает:

метод getMessage ()

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

Введите:

"Что то пошло не такjavax.mail.MessagingException: Could not to SMTP host: localhost, port 25; nested exception is : java.net.Connection refused connect"

Если я закомментирую

sentMessage(chan);//поменять куда вставить

Я получу сообщение от slack на почту.

Это моя программа на Java.

       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("tm12018@yandex.ru",
            "test123456");

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

            // Подключение к почтовому серверу
            store.connect("imap.yandex.ru", "tm12018@yandex.ru", "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);

        }
    }

1 Ответ

0 голосов
/ 01 октября 2018

Похоже, что ответ говорит вам, что нет никакого процесса (или, по крайней мере, не хоста электронной почты), который прослушивает ваш локальный порт 25. Вы уверены, что он есть?Что происходит, когда вы делаете telnet localhost 25?

...