2

I'm currently working on a project that involves the creation of a .jar file. 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.

(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.

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  
user207421
  • 305,947
  • 44
  • 307
  • 483
Scarl
  • 950
  • 5
  • 16
  • 31
  • 1
    Are you literally trying to execute that code? Do you understand anything of what it's doing? For the record, it tries to access the mail server of gmail with "user@gmail.com" as the user, and "password" as the password. I doubt that user@gmail.com is your real gmail address. And even if it is, I doubt your password is "password". If it is, you'd better change it now. – JB Nizet Sep 28 '14 at 16:59
  • @JBNizet yes I know what this code is trying to do and now neither is my real password nor email, I put that in to demonstrate that the username is where the email address should be inserted and "password" is the where the real password should be inserted – Scarl Sep 29 '14 at 03:24
  • Can you try changing SMTP host to smtp.googlemail.com ? – Wit Wikky Sep 29 '14 at 03:54
  • @ManojSolanki you're referring to this line of code: final String smtp_host = "smtp.gmail.com"; I just changed it and it's still giving me the same error message – Scarl Sep 29 '14 at 04:07

3 Answers3

2

You're setting smtp_host but you're never using it.

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

You're trying to connect to 'localhost' instead of gmail.com. That's becase you're not setting mail.smtp.host anywhere.

And why are you setting an SSL socket factory in the non-TLS case?

user207421
  • 305,947
  • 44
  • 307
  • 483
2

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();
    }
    }
   } 
Anptk
  • 1,125
  • 2
  • 17
  • 28
  • its worked successfully for me, if this code is not working for you, check your jar files and its versions. – Anptk Sep 29 '14 at 04:45
  • Thanks it did, I was also also able to get an attachment working as well, the only thing I'm left with is receiving the results after my jar file gets executed, do you possibly know if jar files has some sort of java methods for that? – Scarl Sep 29 '14 at 04:53
  • I actually got it to work, it was a matter of assigning the "from" & "to" respectively. Basically if I want a "jar" file's result to be emailed to me once it's running, I should assign the "from" & "to" to be my email . Well at least that's how I got it to work – Scarl Oct 06 '14 at 16:53
  • I am exact same issue with configuration do everything I know, at https://stackoverflow.com/questions/51871429/unable-to-send-email-on-error-from-logback please help. – Raghuveer Aug 16 '18 at 11:59
2

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.

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

found this in Access protection log and requested my admin to remove that rule.

Try this might help you.

Karthik M
  • 21
  • 3