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