如果您为emailSenderAddress和emailSenderPassword提供正确的值,则此片段在Netbeans和命令行中以调试模式工作。 但是,如果不添加导入DataHandler,则它仅在调试模式下起作用。
public class mailTest {
// dummy DataHandler to be sure to keep the import !
private DataHandler dh;
private void prepareMessage() {
java.util.Properties props = System.getProperties();
props.put("mail.smtps.host", "smtp.gmail.com");
props.put("mail.smtps.auth", "true");
// simple class derived from Authenticator not relevant for the current discussion
GMailAuthenticator auth = new GMailAuthenticator(<emailSenderAddress>, <emailSenderPassword>);
javax.mail.Session session = javax.mail.Session.getInstance(props, auth);
javax.mail.Message msg = new javax.mail.internet.MimeMessage(session);
System.out.println("new MimeMessage ok !");
}
public static void main(String[] args) {
mailTest mt = new mailTest();
mt.prepareMessage();
}
}
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator(String username, String password) {
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pw);
}
}
答案 0 :(得分:0)
您使用的是哪个JDK版本? DataHandler是javax.activation(JavaBeans激活框架,又名JAF)API的一部分,该API包含在JDK 8和更早版本中,但不包含在JDK 11中。无论您是否在程序中显式使用JavaMail,JavaMail都需要JAF。在JDK 11上,您需要将其显式添加到项目中。如果您有Maven项目,则可以在com.sun.activation:javax.activation:1.2.0上添加依赖项。