Java 邮件异常错误未知 SMTP 主机:smtp.gmail.com 是电子邮件未发送

Java Mail Exception Error Unknown SMTP host: smtp.gmail.com is E-mail is not send

我正在尝试通过 Gmail 发送电子邮件,但出现异常“未知 SMTP 主机:smtp.gmail.com”。 我已经开启 不太安全的应用程序访问和两步验证应该关闭

public class MonitoringMail
{
    public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
    {
        boolean debug = false;
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable","true");
        props.put("mail.smtp.auth", "true");

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

        
          Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getDefaultInstance(props, auth);

            session.setDebug(debug);
        
        try
        {
            
            
            Transport bus = session.getTransport("smtp");
            bus.connect();
            Message message = new MimeMessage(session);
        
         //X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
            
             message.addHeader("X-Priority", "1");
             message.setFrom(new InternetAddress(from));
             InternetAddress[] addressTo = new InternetAddress[to.length];
             for (int i = 0; i < to.length; i++)
             addressTo[i] = new InternetAddress(to[i]);
             message.setRecipients(Message.RecipientType .TO, addressTo);
             message.setSubject(subject);
                  
             
             BodyPart body = new MimeBodyPart();

            // body.setText(messageBody);
            body.setContent(messageBody,"text/html");

             MimeMultipart multipart = new MimeMultipart();
             multipart.addBodyPart(body);
            // multipart.addBodyPart(attachment);
             message.setContent(multipart);
             Transport.send(message);
             System.out.println("Sucessfully Sent mail to All Users");
             bus.close();
            
        }
        catch (MessagingException mex)
        {
            mex.printStackTrace();
        }       
    } 

它可以更早地工作,但一周后我遇到了异常。 我尝试解决这个异常,我花了 3 天时间,但我无法解决这些问题,请尝试解决这个问题。

SMTP 有 2 个不同的端口 SSL 465 的端口 TLS/STARTTLS 的端口 587 您尝试使用其他端口了吗?

请尝试使用端口 25。

props.setProperty("mail.smtp.port", "25");

我了解到您设置了 Gmail 帐户并启用了安全性较低的应用程序,但 Gmail 帐户在闲置一段时间后会自动关闭“允许安全性较低的应用程序”选项。如果此代码之前有效,请尝试再次检查您的 Gmail 帐户设置。

在我的例子中,我更改了端口之后它工作正常