无法连接到主机,端口:smtp.gmail.com,587

时间:2018-03-26 10:56:19

标签: port host

我正在尝试通过gmails SMTP Server使用JavaMail发送电子邮件。但是这段代码。 我在NetBeans上运行此代码。

编译时代码中没有错误,但是它给出了运行时错误。我该怎么办?

import java.util.Properties;    
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailUsingGMailSMTP {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "xyz@gmail.com";//change accordingly    
      // Sender's email ID needs to be mentioned
      String from = "abc@gmail.com";//change accordingly
      final String username = "abc";//change accordingly
      final String password = "xxxxxx";//change accordingly    
      // Assuming you are sending email through relay.jangosmtp.net
      String host = "smtp.gmail.com";    
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", 587);    
      // Get the Session object.
      Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }
      });    
      try {
         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);    
         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));    
         // Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));    
         // Set Subject: header field
         message.setSubject("Testing Subject");    
         // Now set the actual message
         message.setText("Hello, this is sample for to check send "
            + "email using JavaMailAPI ");    
         // Send message
         Transport.send(message);    
         System.out.println("Sent message successfully....");    
      } catch (MessagingException e) {
            System.out.println(e);
      }          
   }
}

当我跑步时,我遇到了这个错误:

  

com.sun.mail.util.MailConnectException:无法连接到主机,端口:smtp.gmail.com,587;超时-1;

     

嵌套异常是:java.net.ConnectException:连接超时:connect

我不知道这个代码有什么错误? 我该如何解决这个问题? 有人可以帮忙吗?

0 个答案:

没有答案