0

Below is a simple test class I wrote to send email using Java. I am trying to send the message from my localhost. But I get the following error message:

javax.mail.MessagingException: Unknown SMTP host: http://localhost:8080/;
nested exception is:
java.net.UnknownHostException: http://localhost:8080/
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1280)

I change to host value to simply "localhost" but I get the same problem. Any ideas on a fix? Would a real server work?

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

public class MyEmail {

public static void main(String... args) {
    String to = "me@email.com";
    String from = "other@email.com";
    String host = "http://localhost:8080/";

    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host",host);
    Session session = Session.getDefaultInstance(properties);

    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
        message.setSubject("This is a subject");
        message.setText("The text is what it is the text");
        Transport.send(message);
        System.out.println("Successful");
    }catch(MessagingException mx){
        mx.printStackTrace();
    }
}
}
tribal
  • 653
  • 2
  • 13
  • 26

2 Answers2

3

The host value should just be the host name or ip address. This is not HTTP.

To set the port, set the property mail.smtp.port to your port number (as a string)

Erik Ekman
  • 2,051
  • 12
  • 13
  • I changed it to "25" and that didn't work. Thanks for responding. – tribal Feb 22 '12 at 20:32
  • What kind of SMTP server are you running? Anything you can use with a browser will not work. – Erik Ekman Feb 22 '12 at 20:36
  • I found the answer eventually [here](http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail#47452) – tribal Feb 22 '12 at 22:02
0

You require a running mail ( SMTP ) server at the host you specified for sending any messages . The host corresponds to the address of the SMTP server ( without http:// ) and the port corresponds to the configured smtp port . Looking at your issue , there is a problem making connection with the SMTP server .Make sure you correct your parameters for host and port according to a running smtp server and try again .

jay
  • 791
  • 8
  • 20
  • I found the answer eventually [here](http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail#47452) – tribal Feb 22 '12 at 22:01