Balaji Muthusamy
Balaji Muthusamy

Reputation: 23

java mail API's Transport function not working

I tried smtp.gmail.com to send mail using java API, when i used Transport.send(Mimemessage) it shows error, username and password not accepted.

I had followed this link and done everything, it still did not work.

Then, I tried using SmtpTransport, it works.

My question is, why did Transport.send() not work and how SmtpTransport worked.

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

public class Email {

    Email(String from, String pwd, String to, String sub, String msg) {
        System.out.println("Entered");
        Properties prop = new Properties();
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.user", from); // User name
        prop.put("mail.smtp.password", pwd); // password
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.auth", "true");

        Authenticator a = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("from", "pwd");
            }
        };
        System.out.println("Authenticating");
        Session ses = Session.getDefaultInstance(prop, a);
        System.out.println("Obtained sesion");
        System.out.println(ses);
        try {
            MimeMessage m = new MimeMessage(ses);

            m.setFrom(new InternetAddress(from));
            m.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            m.setSubject(sub);
            m.setText(msg);
            System.out.println("Message constructed");
            Transport.send(m); // / This method causes error
            System.out.println("transported");
            System.out.println("send successfully");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Email("[email protected]", "xxxxxx", "[email protected]",
                "JavaMail", "Firstmail");
    }
}

Upvotes: 0

Views: 544

Answers (1)

Sunil
Sunil

Reputation: 447

You have make a mistake by passing from and pwd hardcoded into PasswordAuthentication constructor. Just remove hard coded values and pass from and pwd into method.

I have made correction in your class as given bellow code .

public class Email {


Email(final String from,final String pwd,String to,String sub,String msg){
....

  Authenticator a=new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication()
      {
         return new PasswordAuthentication(from,pwd); 
      }
 };
 ...

}

Upvotes: 4

Related Questions