我正在尝试在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.*;
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();
}
}
}
我使用了教程,这基本上就是他们使用的代码。我试图改变主机,但每次都失败了。
答案 0 :(得分:2)
如果你使用gmail id发送邮件你必须使用gmail主机服务器地址'mail.smtp.host'你不能使用localhost所以你试试这个。
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...","");
}
}
并禁用您的PC防病毒和防火墙,并在Google帐户设置中启用“访问安全性较低的应用”。