尝试使用 smtp 发送邮件,使用了所有必要的 jar 文件(mail.jar 和 activation.jar),但总是显示此错误
我使用了两个类,一个是发送电子邮件,另一个是调用该文件中的函数
sendmail.java 的代码
import javax.mail.*;
import javax.mail.internet.*;
class SendMail{
public static void send(String from,String password,String to,String sub,String msg){
//Get properties object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//get Session
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(sub);
message.setText(msg);
//send message
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {throw new RuntimeException(e);}
}
}
testmail.java 的代码
public class testmail{
public static void main(String[] args) {
//from,password,to,subject,message
SendMail.send("myemail","mypassword","reciever","hello javatpoint","How r u?");
System.out.println("message sent successfully");
//change from, password and to
}
}
这两个文件都在编译,但是当我执行 testmail 文件时,会显示错误
我使用的是 apache tomcat 9.0 服务器