以下通过我们自己的服务器发送电子邮件的代码提供了AuthenticationFailedException
String to = "to@abc.co.in";
String from = "from@abc.co.in";
String host = "Mail.abc.co.in";
String message= null;
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
Message simpleMessage = new MimeMessage(session);
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject("-------------");
simpleMessage.setContent(message, "text/html");
Transport trans = session.getTransport("smtp");
trans.connect("Mail.abc.co.in", 587, "example@abc.co.in", "password");
trans.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
您使用什么SMTP服务器?
某些服务器需要TSL / SSL(例如Google smtp) 尝试通过ssl配置您的授权。
以下是我通过ssl连接Google smtp的版本:
private void configSession() throws IOException {
// Configuring smtp
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.socketFactory.port", smtpSocketFactoryPort);
properties.put("mail.smtp.socketFactory.class", smtpSocketFactoryClass);
properties.put("mail.smtp.auth", smtpAuth);
properties.put("mail.smtp.port", smtpPort);
session = Session.getInstance(properties, new MailAuthenticator(username, password));
}
private class MailAuthenticator extends Authenticator {
private String username;
private String password;
MailAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
public void send(){
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
message.setSubject(messageTitle);
message.setText("Hello");
Transport.send(message);
} catch (Exception e) {
logger.error("Error sending email:", e);
}
属性:
mail.smtp.host=smtp.gmail.com
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.auth=true
mail.smtp.port=465