在netbeans中使用javamail错误
我试图在Netbeans中使用javamail函数,但一直都会出错在netbeans中使用javamail错误,java,netbeans,jakarta-mail,Java,Netbeans,Jakarta Mail,我试图在Netbeans中使用javamail函数,但一直都会出错 javax.mail.MessagingException: Could not connect to SMTP host: 10.101.3.229, port: 25; nested exception is: java.net.ConnectException: Connection timed out: connect 我使用的代码是: import java.util.*; import javax.mail.*;
javax.mail.MessagingException: Could not connect to SMTP host: 10.101.3.229, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
我使用的代码是:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class TESTINGemail {
public static void main(String [] args)
{
String to = "abcd@gmail.com";
String from = "web@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
我使用了一个教程,这基本上就是他们使用的代码。我试图更换主机,但每次都失败了 如果使用gmail id发送邮件,则不能使用localhost。您必须使用gmail主机服务器地址“mail.smtp.host”,因此请尝试此方法
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class MailSender {
public static void send (String to,String message1,String subject,String ss)
throws Exception {
String host ="smtp.gmail.com";
String from="from@gmail.com";
String password="Your password";
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "465");
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom( new InternetAddress(from));
message.addRecipient( Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(message1);
Transport transport = session.getTransport("smtps");
transport.connect(host,from, password);
transport.sendMessage(message, message.getAllRecipients());
System.out.println("mail has been sent");
}
public static void main(String arg[]) throws Exception
{
MailSender m=new MailSender();
m.send("to@gmail.com", "hello ..", "test mail...","");
}
}
同时禁用电脑防病毒和防火墙,并在谷歌帐户设置中启用“访问不太安全的应用程序”
.JavaMail常见问题解答已经发布。