下面發佈的代碼適用於通過帶有SSL的STMP發送電子郵件。 現在SMTP更改爲TSL,我不會設法用它發送電子郵件。 我試了幾件東西,如添加使用TSL通過SMTP發送電子郵件
props.put("mail.smtp.starttls.enable","true");
但它是沒有用的。
錯誤代碼說:
「javax.mail.MessagingException的:無法連接到SMTP主機:exch.studi.fhws.de,端口:587; 嵌套的例外是: 的javax.net.ssl .SSLException:無法識別的SSL消息,明文連接?「
任何想法?
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
String d_email = "...",
password = "...",
host = "...",
port = "25",
mailTo = "...",
mailSubject = "test",
mailText = "test";
public SendMail()
{
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(mailText);
msg.setSubject(mailSubject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
Transport.send(msg);
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public static void main(String[] args)
{
TextClass tc = new TextClass();
}
private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(d_email, password);
}
}
}
看這個博客的文章:http://blogs.oracle.com/apanicker/entry/java_code_for_smtp_server – Marcelo
謝謝,代碼以上是相同的 - 我用這個例子。 – nerc