2014-11-04 2 views
1

Я пытаюсь создать программу с использованием JavaMail API, однако я продолжаю получать следующее сообщение об ошибке.Ошибка API JavaMail (javax.mail.NoSuchProviderException: недопустимый поставщик)

javax.mail.NoSuchProviderException: invalid provider 
at javax.mail.Session.getTransport(Session.java:738) 
at javax.mail.Session.getTransport(Session.java:682) 
at javax.mail.Session.getTransport(Session.java:662) 
at EmailAutoResponder2.main(EmailAutoResponder2.java:56) 

Я не смог его решить, прочитав онлайн, так как все их решения по-прежнему дали мне то же сообщение.

Вот код Java:

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 

public class EmailAutoResponder2 { 

public static void main(String[] args) { 

    String to = "[email protected]"; 
    String from = "[email protected]"; 

    Properties properties = System.getProperties(); 

    properties.setProperty("mail.store.protocol", "imaps"); 

    Session session1 = Session.getInstance(properties); 

    //If email received by specific user, send particular response. 
    Properties props = new Properties(); 

    props.put("mail.imap.auth", "true"); 
    props.put("mail.imap.starttls.enable", "true"); 
    props.put("mail.imap.host", "imap.videotron.ca"); 
    props.put("mail.imap.port", "143"); 

    Session session2 = Session.getInstance(props, new Authenticator() { 

       protected PasswordAuthentication getPasswordAuthentication() { 
         return new PasswordAuthentication("[email protected]", "password"); 
      } 
     }); 

    try { 
     Store store = session2.getStore("imap"); 
     store.connect("imap.videotron.ca", "[email protected]", "password"); 
     Folder fldr = store.getFolder("Inbox"); 
     fldr.open(Folder.READ_ONLY); 
     Message msgs[] = fldr.getMessages(); 
      for(int i = 0; i < msgs.length; i++){ 
       System.out.println(InternetAddress.toString(msgs[i].getFrom())); 

      if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){ 

       MimeMessage message = new MimeMessage(session1); 

       message.setFrom(new InternetAddress(from)); 
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
       message.setSubject("Subject"); 
       message.setText("Message"); 

       String protocol = "imap"; 
       props.put("mail." + protocol + ".auth", "true"); 

       Transport t = session2.getTransport("imap"); 
       try { 
        t.connect("[email protected]", "password"); 
        t.sendMessage(message, message.getAllRecipients()); 
       } 
       finally { 
        t.close(); 
       } 

      } 
      } 

    } 

    catch(MessagingException mex){ 
     mex.printStackTrace(); 
    } 

    catch(Exception exc) { 

    } 

    } 

    } 

Спасибо!

+0

Вы не настройки ваших свойств системы в любом месте, все они находятся в приемлю ваши собственные свойства. –

ответ

1

Вы подключаетесь к локальному хосту для отправки сообщения. У вас есть почтовый сервер, работающий на вашем локальном компьютере? Возможно нет. Вам необходимо установить свойство mail.smtp.host. Вам также может потребоваться указать имя пользователя и пароль для вашего почтового сервера; см. JavaMail FAQ.

+0

Я следовал инструкции из вашей ссылки, и теперь я получаю сообщение об ошибке: ** javax.mail.NoSuchProviderException: недопустимый поставщик \t на javax.mail.Session.getTransport (Session.java:724) \t в javax.mail .Session.getTransport (Session.java:668) \t в javax.mail.Session.getTransport (Session.java:648) \t в EmailAutoResponder2.main (EmailAutoResponder2.java:57) ** –

+0

Покажите мне, как вы обновили свой код. Какой протокол вы используете? "SMTP"? "SMTPS"? Что-то еще не сработает с исключением выше. –

+0

Я использую imap. Я обновил свой вопрос с новым кодом и сообщением об ошибке. –

-1

Следующий код может решить вашу проблему

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 

public class Email { 

private static String USER_NAME = "username"; // GMail user name (just the part before "@gmail.com") 
private static String PASSWORD = "password"; // GMail password 

private static String RECIPIENT = "[email protected]"; 

public static void main(String[] args) { 
String from = USER_NAME; 
String pass = PASSWORD; 
String[] to = { RECIPIENT }; // list of recipient email addresses 
String subject = "Java send mail example"; 
String body = "hi ....,!"; 

sendFromGMail(from, pass, to, subject, body); 
} 

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { 
Properties props = System.getProperties(); 
String host = "smtp.gmail.com"; 

props.put("mail.smtp.starttls.enable", "true"); 

props.put("mail.smtp.ssl.trust", host); 
props.put("mail.smtp.user", from); 
props.put("mail.smtp.password", pass); 
props.put("mail.smtp.port", "587"); 
props.put("mail.smtp.auth", "true"); 


Session session = Session.getDefaultInstance(props); 
MimeMessage message = new MimeMessage(session); 

try { 


    message.setFrom(new InternetAddress(from)); 
    InternetAddress[] toAddress = new InternetAddress[to.length]; 

    // To get the array of addresses 
    for(int i = 0; i < to.length; i++) { 
     toAddress[i] = new InternetAddress(to[i]); 
    } 

    for(int i = 0; i < toAddress.length; i++) { 
     message.addRecipient(Message.RecipientType.TO, toAddress[i]); 
    } 



    message.setSubject(subject); 
    message.setText(body); 


    Transport transport = session.getTransport("smtp"); 


    transport.connect(host, from, pass); 
    transport.sendMessage(message, message.getAllRecipients()); 
    transport.close(); 

} 
catch (AddressException ae) { 
    ae.printStackTrace(); 
} 
catch (MessagingException me) { 
    me.printStackTrace(); 
    } 
} 
} 
Смежные вопросы