简体   繁体   English

通过Java发送电子邮件-javax.mail.MessagingException:无法连接到SMTP主机:localhost,端口:587;

[英]Sending emails through Java - javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;

I'm currently working on a project that involves the creation of a .jar file. 我目前正在从事一个涉及创建.jar文件的项目。 The following is to be achieved, I'm supposed to export/read the path of a friend's registry, once this is done I'm supposed to get the result back via email. 要实现以下目标,我应该导出/读取朋友注册表的路径,一旦完成,我应该通过电子邮件取回结果。 The whole concept is in creating the jar file and once it's clicked I get the results through my email since I actually sent it through email. 整个概念是创建jar文件,一旦单击它,由于实际上是通过电子邮件发送的,因此我会通过电子邮件获取结果。

(I hope this makes sense) (我希望这是有道理的)

So first, I've combined the following code to actually read the registry and display the keys ( i got it from the popular post on stack overflow for read/write registries) so the reading process is working fine, now my problem is with the email code, 因此,首先,我组合了以下代码以实际读取注册表并显示键(我从堆栈溢出的流行帖子中获取了读取/写入注册表),因此读取过程运行正常,现在我的问题是电子邮件代码,

(I'm not quite sure who the original owner to this code is but full credit goes it him) I'm trying to get the basic concept of this email code to work so that I can continue working on sending my jar file as an attachment and link it to my code in a way when a user clicks on the jar file, the registry results will be emailed back to me. (我不太确定此代码的原始所有者是谁,但他应全力以赴)。我正在尝试使此电子邮件代码的基本概念生效,以便我可以继续将jar文件作为附件,并将其链接到我的代码,方式是当用户单击jar文件时,注册表结果将通过电子邮件发送给我。

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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailCode {

  public static void main(String[] args) throws Exception {


     final String smtp_host = "smtp.gmail.com";
    final String smtp_username = "user@gmail.com";
    final String smtp_password = "password";
    final String smtp_connection = "TLS";  // Use 'TLS' or 'SSL' connection

    final String toEmail="tomail@hotmail.com";
    final String fromEmail="**@gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");

   if (smtp_connection.equals("TLS")) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.port", "587");
    } else{
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.port", "465");
    }

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(smtp_username, smtp_password);
            }
      });

    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
        msg.addRecipient(Message.RecipientType.TO,
                         new InternetAddress(toEmail, "Mr. Recipient"));
        msg.setSubject("Welcome To JavaMail API");
        msg.setText("JavaMail API Test - Sending email example through remote smtp server");
        Transport.send(msg);
        System.out.println("Email sent successfully...");
    } catch (AddressException e) {
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
   }
 }

This is the error message I'm getting: 这是我收到的错误消息:

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect  

You're setting smtp_host but you're never using it. 您正在设置smtp_host但从未使用过。

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;

You're trying to connect to 'localhost' instead of gmail.com. 您正在尝试连接到“ localhost”而不是gmail.com。 That's becase you're not setting mail.smtp.host anywhere. 那是因为您不在任何地方设置mail.smtp.host

And why are you setting an SSL socket factory in the non -TLS case? 以及为什么要在 -TLS情况下设置SSL套接字工厂?

The following code may help you to solve your problem, its working........ 以下代码可以帮助您解决问题,它的工作.....

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class Email {

private static String USER_NAME = "username";  // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "password"; // GMail password

private static String RECIPIENT = "xxxxx@gmail.com";

public static void main(String[] args) {
    String from = USER_NAME;
    String pass = PASSWORD;
    String[] to = { RECIPIENT }; // list of recipient email addresses
    String subject = "Java send mail example";
    String body = "hi ....,!";

    sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
  String host = "smtp.gmail.com";

    props.put("mail.smtp.starttls.enable", "true");

    props.put("mail.smtp.ssl.trust", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");


    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {


        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }



        message.setSubject(subject);
        message.setText(body);


        Transport transport = session.getTransport("smtp");


        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }
    catch (AddressException ae) {
        ae.printStackTrace();
    }
    catch (MessagingException me) {
        me.printStackTrace();
    }
    }
   } 

Please check your Antivirus/Malware. 请检查您的防病毒/恶意软件。

If you are using corporate developer machine please contact your administrator to remove that access protection rule. 如果您使用的是公司开发人员计算机,请与管理员联系以删除该访问保护规则。

I had the same problem, my McAfee was blocking all the request. 我遇到了同样的问题,我的McAfee阻止了所有请求。

Blocked by port blocking rule C:\\PROGRAM FILES\\JAVA\\JDK1.8.0_74\\BIN\\JAVAW.EXE Anti-virus Standard Protection:Prevent mass mailing worms from sending mail 0:0:0:0:0:ffff:4a7d:7e6d:587 被端口阻止规则C:\\ PROGRAM FILES \\ JAVA \\ JDK1.8.0_74 \\ BIN \\ JAVAW.EXE阻止防病毒标准保护:防止大量邮件蠕虫发送邮件0:0:0:0:0:ffff:4a7d: 7e6d:587

found this in Access protection log and requested my admin to remove that rule. 在访问保护日志中找到了此内容,并要求我的管理员删除该规则。

Try this might help you. 试试这个可能对您有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 发送邮件错误,javax.mail.MessagingException:无法连接到SMTP主机:本地主机,端口:25; - Sending mail error, javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,端口:587; java.net.NoRouteToHostException:主机没有路由 - javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; java.net.NoRouteToHostException: No route to host javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:587 - javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587 邮件服务GAE问题-发送邮件异常“ javax.mail.MessagingException:无法连接到SMTP主机:localhost,端口:25;” - Mail service GAE issue - sending mail exception “javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;” javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,端口:587无法管理解决此问题 - javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587 Can not manage to solve this problem javax.mail.MessagingException:无法连接到SMTP主机:localhost,端口:25; - javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; Java错误javax.mail.MessagingException:无法连接到SMTP主机: - Java error javax.mail.MessagingException: Could not connect to SMTP host: javax.mail.MessagingException:无法连接到 SMTP 主机:本地主机,端口:25 - javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25 javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:465; - javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; java.lang.RuntimeException:javax.mail.MessagingException:无法连接到SMTP主机:smtp.gmail.com,端口:465 - java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM