![](/img/trans.png)
[英]AuthenticationFailedException error while sending SMTP email
[英]AuthenticationFailedException: failed to connect error while sending email
以下通過我們自己的服務器發送電子郵件的代碼提供了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();
}
您使用什么SMTP服務器?
在某些服務器(例如Google smtp)中需要TSL / SSL。請嘗試通過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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.