1客户端未通过身份验证

1客户端未通过身份验证

我总是收到“ com.sun.mail.smtp.SMTPSendFailedException:530 5.7.1客户端未通过身份验证”错误,有人可以告诉我我的代码在做什么错吗?

Properties mailprops = new Properties();
mailprops.setProperty("mail.transport.protocol", "smtp");
mailprops.setProperty("mail.smtp.host", "MyHost");
mailprops.setProperty("mail.smtp.user", "UserName");
mailprops.setProperty("mail.smtp.password", "Password");

Session mailSession = Session.getDefaultInstance(mailprops, null);
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(mySubject);
message.addRecipient(To);
message.addFrom(from address);

try{
Transport.send(message);
}catch (SendFailedException sfe) {
}catch (MessagingException mex) {
}

最佳答案

尝试以下方法,
提供Authenticator对象以创建session对象

public class MailWithPasswordAuthentication {
public static void main(String[] args) throws MessagingException {
new MailWithPasswordAuthentication().run();
}
private void run() throws MessagingException {
Message message = new MimeMessage(getSession());
message.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
message.addFrom(new InternetAddress[] { new InternetAddress("[email protected]") });
message.setSubject("the subject");
message.setContent("the body", "text/plain");
Transport.send(message);
}
private Session getSession() {
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", "mail.example.com");
properties.setProperty("mail.smtp.port", "25");
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "auth-user";
String password = "auth-password";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}

07-26 09:37