收到smtp错误:javax.mail.NoSuchProviderException:无效的协议:null

时间:2015-01-08 01:42:22

标签: java spring spring-mvc smtp javamail

我正在尝试设置JavaMail来阅读smtp服务器上通过CentOS 7收到的电子邮件,其中postfixmailx已安装并正常运行正常。我创建了一个名为POJO的{​​{1}},其中包含一个名为TestEmail.java的方法。 read() Spring MVC实例化controller并调用TestEmail.java方法,但此调用会引发以下错误:

read.()

我已阅读有关此错误的其他帖子,包括this onethis one。但其他帖子与发送电子邮件有关。我的错误与阅读收到的电子邮件有关。所以这个新帖子是不同的。

以下是抛出错误的方法:

javax.mail.NoSuchProviderException: Invalid protocol: null  

我将以下内容添加为web.xml中的最后一个节点:

public void read(){
    //lookup the java mail session
    InitialContext ic;
    try {
        ic = new InitialContext();
        String snName = "java:comp/env/mail/Session";
        Session session = (Session)ic.lookup(snName);
        //Get a Store object from the Session, then connect to the mail server using the Store object’s connect() method. You must supply a mail server name, a mail user name, and a password.
        Store store = session.getStore();
        store.connect("mail.smtp.host", "someuser", "somepassword"); 
        //Get the default folder, then get the INBOX folder:
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX"); 
        //It is efficient to read the Message objects (which represent messages on the server) into an array:
        Message[] messages = folder.getMessages();
        int num_msgs = messages.length;
        System.out.println("num_msgs is: "+num_msgs);
    } 
    catch (NamingException e) {e.printStackTrace();} 
    catch (MessagingException me){me.printStackTrace();}
}

我将以下行添加到/opt/tomcat/conf/context.xml:

<resource-ref>
  <description>
    Resource reference to a factory for javax.mail.Session
    instances that may be used for sending electronic mail
    messages, preconfigured to connect to the appropriate
    SMTP server.
  </description>
  <res-ref-name>
    mail/Session
  </res-ref-name>
  <res-type>
    javax.mail.Session
  </res-type>
  <res-auth>
    Container
  </res-auth>
</resource-ref>  

引用调用上面<Resource name="mail/Session" auth="Container" type="javax.mail.Session" mail.smtp.host="localhost"/> 方法的堆栈跟踪中的行是:

read()

这是完整的堆栈跟踪:

at some.package.SomeController.processSomeForm(SomeController.java:277)  

0 个答案:

没有答案