当前位置: 首页 > 知识库问答 >
问题:

通用域名格式。太阳邮政util。MailConnectException:无法连接到主机,端口:smtp。gmail。com,587超时-1

林运浩
2023-03-14

错误:

通用域名格式。太阳邮政util。MailConnectException无法连接到主机、端口smtp。gmail。com,587超时-1嵌套异常是java。网ConnectException:连接被拒绝:连接

我的源代码是:

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

共有1个答案

吉凯捷
2023-03-14

尝试另一个端口:465并添加更多道具

    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");
 类似资料: