javax.mail.AuthenticationFailedException错误,请高手们帮帮忙
我在servlet中写的邮件发送,老是提示javax.mail.AuthenticationFailedException错误,查了半天也没查出来是什么原因,请各位高手帮帮忙,小妹感激不尽,源码如下:
String smtpServer = request.getParameter( "txtserver ");
String emailTo = request.getParameter( "txtto ");
String fromemail = request.getParameter( "txtfrom ");
String subject = request.getParameter( "txtsubject ");
String body = request.getParameter( "txtmessage ");
try
{
Properties props = new Properties() ;
props.put( "mail.transport.protocol ", "smtp ");
props.put( "mail.smtp.auth ", "true ");
props.put( "mail.smtp.host ",smtpServer);
props.put( "mail.smtp.port ", "25 ");
Session mailsession = Session.getInstance(props);
Message msg = new MimeMessage(mailsession);
msg.setFrom(new InternetAddress(fromemail));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(emailTo));
msg.setSentDate(new Date());
msg.setSubject(subject);
msg.setText(body);
msg.saveChanges() ;
// Transport transport;
// transport = mailsession.getTransport( "smtp ");
// transport.connect((String)props.get( "smtp.163.com "), "caojunkeke ", "06240624 ");
Transport.send(msg);
msg.writeTo(System.out );
out.print( "邮件已成功发送到 ");
}
catch(Exception e)
{
System.out.println(e);
}
[解决办法]
需要验证,当然不行了
final String username = "username ";
final String password = "password ";
//使用验证
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username,
password);
}
});
把username,password改成你邮箱的用户名和密码
[解决办法]
有点问题
[解决办法]
当今mail服务器大多都是通过认证才能发信的,现在的网上介绍javamail发信的文章都没有深入到有关认证的方面,除非自己装一个open relay的mail服务器,但是这样有很危险,本人根据自己工作中用的javamail的方法说一下自己的用法,不对的地方请大家多指教.
首先设置属性Properties props = new Properties();
props.put( "mail.smtp.host ",host);
props.put( "mail.smtp.auth ", "true ");注意的是此处必须加上true要不然stmp连接的时候不会认证
用Authenticator写认证类下面是本人的认证类
package org.xxx;
import javax.mail.*;
import javax.mail.internet.*;
public class PopupAuthenticator extends Authenticator{
String username=null;
String password=null;
public PopupAuthenticator(){}
public PasswordAuthentication performCheck(String user,String pass){
username = user;
password = pass;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
认证类写完后,在发信的程序中加上
PasswordAuthentication pop = popAuthenticator.performCheck(username,password);
Session mysession=Session.getInstance(props,popAuthenticator);
mailsession加的popAuthenticator
其他的方法和javamail发信的用法相似,在此不累述。