Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is:
C#
public class SendMailBySite {
public static void main(String[] args) {

  String host = "host name";//or IP address
  final String user="user name";;//change accordingly
  final String password="XXXXXX";//change accordingly
  
  String to="mail addr";//change accordingly

   //Get the session object
   Properties props = new Properties();
   props.put("mail.smtp.host",host);
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.socketFactory.fallback", "false");
   props.put("mail.smtp.socketFactory.port", "465");
   
   Session session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
	return new PasswordAuthentication(user,password);
      }
    });

   //Compose the message
    try {
     MimeMessage message = new MimeMessage(session);
     message.setFrom(new InternetAddress(user));
     message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
     message.setSubject("javatpoint");
     message.setText("This is simple program of sending email using JavaMail API");

    //send the message
     Transport.send(message);

     System.out.println("message sent successfully...");

     } catch (MessagingException e) {e.printStackTrace();}
 }
}

and error is:
C#
javax.mail.MessagingException: Could not connect to SMTP host: host name, port: 25;
  nested exception is:
	java.net.ConnectException: Connection refused: connect
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
	at javax.mail.Service.connect(Service.java:313)
	at javax.mail.Service.connect(Service.java:172)
	at javax.mail.Service.connect(Service.java:121)
	at javax.mail.Transport.send0(Transport.java:190)
	at javax.mail.Transport.send(Transport.java:120)
	at com.SendMailBySite.main(SendMailBySite.java:42)
Caused by: java.net.ConnectException: Connection refused: connect
	at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
	at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
	at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
	at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
	at java.net.PlainSocketImpl.connect(Unknown Source)
	at java.net.SocksSocketImpl.connect(Unknown Source)
	at java.net.Socket.connect(Unknown Source)
	at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
	at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:201)
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
	... 7 more
Posted
Updated 10-Jul-13 21:01pm
v2
Comments
Shubhashish_Mandal 11-Jul-13 3:08am    
check the smtp host is running and port is active.
vishal.v.patil 11-Jul-13 3:18am    
i have checking it with telnet command it will gives an error as
Connecting To host_name...Could not open connection to the host, on port 25: Connect failed
Shubhashish_Mandal 11-Jul-13 3:50am    
Then you have to set up smptp host in your local machine.
vishal.v.patil 12-Jul-13 2:32am    
i dont get your meaning.. can u please explain???

Hello,

Can you try with following code. Alternatively if you are using spring framework, then you can try using org.springframework.mail.javamail.JavaMailSenderImpl.
Java
public void doSend(MimeMessage msg, String strHost, int intPort, String strUser, String strPass) {
    String msgId = null;
    Session ses = null;
    Transport trans = null;
 
    try {
        ses = Session.getInstance(new Properties());
        trans = session.getTransport("smtp");
        trans.connect(strHost, intPort, strUser, strPass);
        if (null == msg.getSentDate()) msg.setSentDate(new Date());
        msgId = msg.getMessageID();
        msg.saveChanges();
        if (null == msgId) msg.setHeader(HEADER_MESSAGE_ID, msgId);
        trans.sendMessage(msg, msg.getAllRecipients());
    } catch(AuthenticationFailedException ex) {
        log.error("Unable to authenticate with the mail server!", ex);
    } catch (MessagingException ex) {
        log.error("Unexpected error occurred while sending the message!", ex);
    } finally {
        doCleanup(trans);
        if (ses != null) ses = null;
        if (trans != null) trans = null;
    }
}

private void doCleanup(Transport in) {
    try {
        if (in != null) in.close();
    } catch (MessagingException ex) {
        log.error("Unexpected error occurred while closing the transport!", ex);
    }
}

Regards,
 
Share this answer
 
Comments
vishal.v.patil 11-Jul-13 5:20am    
Sorry bro... but i am not using that framework... thanks for reply!!
Prasad Khandekar 11-Jul-13 10:26am    
Hello,

Have you tried the sample code? It's not related to Spring Framework.

Regards,
vishal.v.patil 12-Jul-13 2:30am    
yes, i am... but its only works with the gmail smtp not for other...
Shubhashish_Mandal 12-Jul-13 3:22am    
to send mail you need to configure a smtp server. Here is one
http://local-smtp-server.en.softonic.com/ . Install it and run it in your local machine.
Once its running , set props.put("mail.smtp.host",localhost);
Because now your smtp server is running in your localhost.
vishal.v.patil 12-Jul-13 3:26am    
but i have the some other website hosting and i am sending from that email id.,
for ex..
i have vishal@xyz.com email account and smtp is mail.xyz.com
so how can i send the mail??
Do NOT use webservers for testing. They refuse connection when you attempt to often or make mistakes.

Use HmailServer[^] for testing. It's a local emailserver for your machine. Please be aware that this one has also a ban-option (switching off ban function is preferable for development).
 
Share this answer
 
Comments
vishal.v.patil 11-Jul-13 7:23am    
thanks for replay ... here is problem is smtp..when i gives it gmail smtp and email it working smoothly....
when i give it another it gives above stacktrace.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900