简体   繁体   中英

Sending email using Java, connecting to a gmail host hangs

I would like to send emails via Java code. I added in my library the following .JARs: log4j.jar, smtp.jar, mailapi.jar,ctivation.jar. And my Java class looks like this:

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

public class SendEmail
{
public static void main(String [] args)
{    
   String to = "abcd@gmail.com";
   String from = "web@gmail.com";
   String host = "smtp.gmail.com";
   Properties properties = System.getProperties();


   properties.setProperty("mail.smtp.host", host);
   properties.setProperty("mail.smtp.starttls.enable", "true");
   properties.setProperty("mail.smtp.auth", "true");

   SmtpAuthenticator authentication = new SmtpAuthenticator();
   javax.mail.Message msg = new MimeMessage(Session
                       .getInstance(properties, authentication));

   try {
       msg.setFrom(new InternetAddress(from));
       msg.setRecipient(Message.RecipientType.TO, 
           new InternetAddress(to));
       msg.setSubject("Subject");
       msg.setText("Working fine..!");
       System.out.println("fine1    !!");
       Transport transport = Session.getDefaultInstance( properties , null).getTransport("smtp");
       System.out.println("fine2    !!");
       transport.connect("smtp.gmail.com" , 465 , "username", "password");
       System.out.println("fine3    !!");
       Transport.send(msg);
       System.out.println("fine!!");
   }
   catch(Exception exc) {
       System.out.println(exc);
   }
}
}

My SmtpAuthenticator class:

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SmtpAuthenticator extends Authenticator {
    public SmtpAuthenticator() {

        super();
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        String username = "user";
        String password = "password";
        if ((username != null) && (username.length() > 0) && (password != null)
                && (password.length() > 0)) {

            return new PasswordAuthentication(username, password);
        }

        return null;
    }
}

When i run my Java application class it prints: fine1 !! fine2 !!

And it hangs. How can I get rid of this problem?

The problem is on this line:

transport.connect("smtp.gmail.com" , 465 , "username", "password");

465 is the port for smtp over ssl (smtps), so either use port 25:

transport.connect("smtp.gmail.com" , 25 , "username", "password");

or change to use smtps

Transport transport = Session.getDefaultInstance( properties , null).getTransport("smtps");

transport.connect("smtp.gmail.com" , 465, "username", "password");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM