java 异常:无法连接到主机,端口:网址:smtp.gmail.com,587超时-1

gopyfrb3  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(361)

错误:
异常无法连接到主机,端口www.example.com,587超时-1嵌套异常是java. net。smtp.gmail.com连接 Connection refused: connect
我的源代码是:

package poidemo;

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 Test_MailTrigger {
  public static void main(String [] args) {

      String to = "xxxx@gmail.com";//change accordingly    

      String from = "yyyy@gmail.com";//change accordingly
      final String username = "yyyy@gmail.com";//change accordingly
      final String password = "*****";//change accordingly    

      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);    

      Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }
      });    
      try {

         Message message = new MimeMessage(session);    

         message.setFrom(new InternetAddress(from));    

         message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));    

         message.setSubject("Testing Subject");    

         message.setText("Hello, this is sample for to check send "
            + "email using JavaMailAPI ");    

         Transport.send(message);    
         System.out.println("Sent message successfully....");    
      } catch (MessagingException e) {
            System.out.println(e);
      }          
   }
}
0kjbasz6

0kjbasz61#

尝试其他端口:465并添加更多 prop

props.put("mail.smtp.port", "465");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

相关问题