【问题标题】:Could not connect to SMTP host exception while sending mail through JavaMail API通过 JavaMail API 发送邮件时无法连接到 SMTP 主机异常
【发布时间】:2020-08-05 22:18:23
【问题描述】:

我正在尝试使用 JavaMail API 向 Gmail 帐户发送电子邮件。我已经完成了以下代码。我想向多个recipents发送邮件。但是它不起作用。它给出了一个异常,例如“无法连接到SMTP主机。发送失败”

package com.cts.email;

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 SendEmail {     
      Properties emailProperties;  
      Session mailSession;
      MimeMessage emailMessage;   
      public static void main(String args[]) throws MessagingException, javax.mail.MessagingException {      
            SendEmail javaEmail = new SendEmail();  
            Session session=javaEmail.setMailServerProperties();   
            javaEmail.createEmailMessage(session);  
          //  javaEmail.sendEmail(); 
            }    
      public Session setMailServerProperties() {    
          Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("my_email","my_password");
                }
            });
                return session; 
      }    

            public void createEmailMessage(Session session) throws MessagingException, javax.mail.MessagingException {    
                  String[] toEmails = { "mahesh.ece9@gmail.com","sandeepreddy792@gmail.com" };  
                  try {
                      for (String to_mail : toEmails) {


                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress("mahesh.ece9@gmail.com"));
                    message.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(to_mail));
                    message.setSubject("Java Email");
                    message.setText("This is an email sent by <b>JavaMail</b> api.");

                    Transport.send(message);



                }
                      System.out.println("Done");
                  }catch (MessagingException e) {
                    throw new RuntimeException(e);
                }   
                }    


                        }

我收到以下异常:

Exception in thread "main" java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
  nested exception is:
    class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.cts.email.SendEmail.createEmailMessage(SendEmail.java:62)
    at com.cts.email.SendEmail.main(SendEmail.java:21)
Caused by: javax.mail.SendFailedException: Sending failed;
  nested exception is:
    class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at com.cts.email.SendEmail.createEmailMessage(SendEmail.java:55)
    ... 1 more

请帮我解决这个问题。

【问题讨论】:

  • 对我有用:至少我可以连接到它。
  • 会不会是网络问题?防火墙、代理、错误的 DNS?

标签: java jakarta-mail


【解决方案1】:

这对我有用:

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 SendMail {


    public static void sendEmail(String to)
    {
        final String username = "your_usename_goes_here";
        final String password = "your_password_goes_here";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        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("fromSomeone@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
            message.setSubject("A testing mail header !!!");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } 

        catch (MessagingException e) 
        {
            // throw new RuntimeException(e);
            System.out.println("Username or Password are incorrect ... exiting !");
        }
    }


    public static void main(String[] args) 
    {
        String to = "toSomeone@gmail.com";
        sendEmail(to);
    }
}

【讨论】:

  • 这也适用于我,如果我要附加一个文件?我应该在哪里添加附件行?
  • 收到错误用户名或密码不正确...退出! ,但是我的gmail地址和密码是正确的吗?另一个原因是什么?
【解决方案2】:

您几乎可以肯定有防火墙或防病毒程序阻止了您的连接能力。请参阅tips for debugging connection problems 的 JavaMail 常见问题解答。

【讨论】:

    【解决方案3】:

    请务必配置您的防病毒软件和防火墙以允许连接

    String user= "FROM@gmail.com";
    String pass= "FROMPASSWORD";
    String mailhost = "smtp.gmail.com";
    
    Properties props= System.getProperties();
    props.put("mail.smtps.host", mailhost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.user", user);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.quitwait", "false");
    
    Session session= Session.getDefaultInstance(props, new javax.mail.Authenticator()  {
    
        @Override
        protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
            return new javax.mail.PasswordAuthentication(user,pass);   
        }
    }); 
    
    MimeMessage message= new MimeMessage(session);
    message.setFrom(new InternetAddress("FROM@gmail.com"));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress("TO@gmail.com"));
    message.setSubject("Checking....");
    message.setText("Successful",user,pass);
    Transport.send(message);
    System.out.println("Sent!");
    

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      相关资源
      最近更新 更多