tags:

views:

356

answers:

2

Hello.

I am using the Javamail API to try and send an email in my java code. The problem is occurring on a particular line.

Part of the code is:

 URLConnection c = u.openConnection();    
 c.setDoInput(false);                         
 c.setDoOutput(true);         
 c.connect();


The error is occurring at the c.connect() line of the code. the error I get is:

connect. Timeout = -1

java.net.ConnectException: Connection refused: connect

And this is all the description I get. I'm not sure how to fix this problem. Please help.

+1  A: 

Take a look at this page to get an example how to send E-Mails. You should use the class Transport to send emails.

public static void send(String smtpServer, String to, String from
   , String subject, String body) throws Exception
  {

      Properties props = System.getProperties();
      // -- Attaching to default Session, or we could start a new one --
      props.put("mail.smtp.host", smtpServer);
      Session session = Session.getDefaultInstance(props, null);
      // -- Create a new message --
      Message msg = new MimeMessage(session);
      // -- Set the FROM and TO fields --
      msg.setFrom(new InternetAddress(from));
      msg.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse(to, false));
      // -- We could include CC recipients too --
      // if (cc != null)
      // msg.setRecipients(Message.RecipientType.CC
      // ,InternetAddress.parse(cc, false));
      // -- Set the subject and body text --
      msg.setSubject(subject);
      msg.setText(body);
      // -- Set some other header information --
      msg.setHeader("X-Mailer", "LOTONtechEmail");
      msg.setSentDate(new Date());
      // -- Send the message --
      Transport.send(msg);
      System.out.println("Message sent OK.");
  }

EDIT:

Because of your comment...

Check if someone blocks the port 25 (Firewall, other application)

the authentication could also be a problem, than you can find a good exampl here

props.put( "mail.smtp.auth", "true" );
Authenticator auth = new SMTPAuthenticator( "[email protected]", "mypassword" );
Markus Lausberg
I have tried an example like this but I get the error "Could not connect to SMTP host: ... port: 25" and it occurs at the Transport.sned(msg) line
Then try again. Check your connection properties. And check if there's a firewall. this is the way to do it.
Stroboskop
A: 

What is the solution for the following error? I am trying to send mail through JavaMail.

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; nested exception is: java.net.ConnectException: Connection timed out: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1227) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322) at javax.mail.Service.connect(Service.java:258) at javax.mail.Service.connect(Service.java:137) at javax.mail.Service.connect(Service.java:86)

Test User