代码如下
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.Message;
import javax.mail.MessagingException;
public class EmailService{
public static void main(String[] args) {
String to="to@gmail.com";//change accordingly
String from="from@";//change accordingly
String password="password";//change accordingly
System.out.println("started");
Properties props = new Properties();
props.put("mail.smtps.host", "localhost");
props.put("mail.smtps.socketFactory.port", "8080");
props.put("mail.smtps.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.auth", "true");
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.connectiontimeout", "90000");
props.put("mail.smtps.timeout", "90000");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
System.out.println("started");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress("to"));
message.setSubject("Nothing Special..");
message.setText("Send Mail By Java Programmm....");
System.out.println("started");
//send message
System.out.println(message);
Transport.send(message);
System.out.println("started");
System.out.println("message sent successfully");
} catch (MessagingException e) {throw new RuntimeException(e);}
}
}
但是我收到了一个错误。我更改了端口详细信息。创建的Javamail会话也是glassfishserver。
javax.mail.internet.MimeMessage@6daa8eb7
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingExcep
tion: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect