我正在尝试使用Java邮件库通过 SiteGround 连接到邮件服务器。
但是每次我看到的都是handshake_failed错误。
即使我去的时候,他们说,我们不能帮你这个支持。
如果有人实施了类似的方法,请分享。
下面是我用来连接到服务器并发送电子邮件的帮助程序类。
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
private String fromEmail;
private String username;
private String password;
private String subject;
private String body;
public SendMailTLS(String fromEmail, String username, String password, String subject) {
this.fromEmail = fromEmail;
this.username = username;
this.password = password;
this.subject = subject;
}
public void setBody(String body){
this.body = body;
}
public boolean send(String toEmail) {
String d_host = "example.com";
try {
Properties props = new Properties();
props.put("mail.smtps.host", d_host);
props.put("mail.smtps.auth", "true");
props.setProperty("mail.smtps.socketFactory.port", "465");
props.setProperty("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject(subject);
// set plain text message
message.setContent(body, "text/html");
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}