这是我的代码
public class MailSend
{
String host, port, emailid,username, password;
Properties props = System.getProperties();
Session l_session = null;
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
public MailSend() {
host = "smtp.mail.yahoo.com";
port = "587";
username = "xxxx@yahoo.com";
password = "xxxxxx";
}
public String sendMail(String toaddress,String subj,String msg)
{
emailSettings();
createSession();
String res= sendMessage("xxxx@yahoo.com", toaddress,subj,msg);
return res;
}
public void emailSettings() {
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
}
public void createSession() {
l_session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxx@yahoo.com", "xxxxx");
}
});
l_session.setDebug(true); // Enable the debug mode
}
public String sendMessage(String emailFromUser, String toEmail, String subject, String msg) {
try {
Address addr = new javax.mail.internet.InternetAddress("xxxxx@yahoo.com","xxxx@yahoo.com");
MimeMessage message = new MimeMessage(l_session);
emailid = emailFromUser;
message.setFrom(addr);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
message.setSubject(subject);
message.setContent(msg, "text/html");
Transport.send(message);
System.out.println("Mail Sent");
} catch (MessagingException mex) {
mex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}//end catch block
return "success";
}
public static void main(String args[])
{
MailSend m=new MailSend();
m.sendMail("xxxxxxx@yahoo.com", "welcome", "testing");
}
当我运行此代码时,我得到以下异常
**com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Authentication required** Exception.
但我正在使用PasswordAuthenticator
。
我不知道为什么会发生此异常。任何人都可以告诉您如何解决此异常,或者请提供任何参考网站。