发送邮件的时出现Unsupported or unrecognized SSL message
时间: 2024-02-03 22:07:57 浏览: 31
出现Unsupported or unrecognized SSL message错误通常是由于SSL/TLS协议版本不匹配导致的。解决此问题的方法是在Java代码中设置SSLContext的协议版本。以下是一个示例代码:
```java
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
final String username = "your_email@example.com";
final String password = "your_email_password";
String recipient = "recipient@example.com";
String subject = "Test Email";
String body = "This is a test email.";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}}, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.example.com", username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```