如果我尝试从java发送邮件,我收到以下错误。我们有Zimbra邮件服务器。
[java] javax.mail.MessagingException: Exception reading response;
[java] nested exception is:
[java] javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
以下是我的代码:
public class SSLEmail {
public void sendMail(){
final String fromEmail = "test@mydomain.com"; //requires valid gmail id
final String password = "test"; // correct password for gmail id
final String toEmail = "test2@gmail.com"; // can be any email id
Properties props = new Properties();
props.put("mail.smtp.username", fromEmail);
props.put("mail.smtp.password", password);
props.put("mail.smtp.protocol", "smtp");
props.put("mail.smtp.host", "mail.hostname.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "true");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(true);
System.out.println("Session created");
EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");
}
}
public class EmailUtil {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("test@mydomain.com"));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
Transport.send(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
}