0

two exception comes in my program.......

  1. cannot connect to the localhost ,port 25

  2. connection refused

code of mail.java is ---

package jMail;

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

public class Mail {

    private String to;
    private String from;
    private String message;
    private String subject;
    private String smtpServ;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSmtpServ() {
        return smtpServ;
    }

    public void setSmtpServ(String smtpServ) {
        this.smtpServ = smtpServ;
    }

    public Exception sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp");
              props.put("mail.smtp.starttls.enable","true");
              props.put("mail.smtp.host","localhost");
              props.put("mail.smtp.auth", "true");
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- 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(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Java Mail Test");
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK.");
              return null;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return ex;
        }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = "[email protected]";
            String password = "javamail";
            return new PasswordAuthentication(username, password);
        }
    }
}

so please tell me what to do & why these exception arises & how can i can mail using the java & localhost as host. ....................... thanks in advance.

5
  • 1
    Do you have an SMTP server running on your machine? Commented Mar 3, 2011 at 19:50
  • Also, you're trying to connect to localhost but authenticate with Gmail credentials. Do you mean to send mail via Gmail's SMTP server instead? Commented Mar 4, 2011 at 4:09
  • i am novice but i think smtp server is running on my m/c because when i use smtp.gmail.com as host then exception Aries -javax.mail.AuthenticationFailedException . Commented Mar 4, 2011 at 9:58
  • if i am wrong then tell me how to check whether SMTP server is running or not in m/c. Commented Mar 4, 2011 at 10:00
  • @dkarp.....SORRY, there is some misprint i was using username = "Java.Mail.CA@localhost"; Commented Mar 4, 2011 at 10:12

2 Answers 2

2

Just follow this code; it is really useful to send email into java desktop and it works.

import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;


import javax.mail.internet.*; 
public class Main
{
    public static void main(String[] args)
    {
        final String username = "[email protected]";
        final String password = "password";
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(username, password);
            }
        });
        try
        {
            String body = "Dear Renish Khunt Welcome";
            String htmlBody = "<strong>This is an HTML Message</strong>";
            String textBody = "This is a Text Message.";
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
            message.setText(htmlBody);
            message.setContent(textBody, "text/html");
            Transport.send(message);
            System.out.println("Done");
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the code snippet to send email.

try {
        String host = "yourHostName";
        String from = "[email protected]";
        String to[] = {"[email protected]"};
        String subject = "Test";

        String message = "Test";

        Properties prop = System.getProperties();
        prop.put("mail.smtp.host", host);
        Session sess1 = Session.getInstance(prop, null);
        MimeMessage msg = new MimeMessage(sess1);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];
        for (int i = 0; i < to.length; i++) {
            toAddress[i] = new InternetAddress(to[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, toAddress);
        msg.setSubject(subject);

        //Fill the message
        msg.setText(message);
        Transport.send(msg);
    } catch (MessagingException me) {
        me.printStackTrace();
    }

What exceptions are you getting while sending emails? Are you sure your SMTP server is listening at default port 25? Are you able to manually send the email via Telnet? Also, turn off any firewall while testing this just to be sure.

3 Comments

1. javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; 2. nested exception is: java.net.ConnectException: Connection refused: connect when i am using username = "Java.Mail.CA@localhost". ,how can i know my SMTP sever is listening at default port & i am novice so i don;t know to manually send email via telnet
Follow this link yuki-onna.co.uk/email/smtp.html on sending email via Telnet.
Check you local firewall as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.