Question

I'm trying to configure servlet to send a message to Gmail, but I'm getting waiting for reply message down my browser window.

Here's the servlet code:

import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;


public class JavaMailServlet extends HttpServlet 
{

public void doGet(HttpServletRequest request,HttpServletResponse response)
{

    try{

        String userName=request.getParameter("p1");
        String password=request.getParameter("p2");;

        Properties props=new Properties();
        props.put("mail.smtp.host","smtp.gmail.com");
        props.put("mail.smtp.port",465);


        Session ses=Session.getInstance(props,null);
        Message msg=new MimeMessage(ses);
        msg.setFrom(new InternetAddress(request.getRequestURI()));
        msg.addRecipient(Message.RecipientType.TO,new InternetAddress("Boyofbackstreet@gmail.com"));
        msg.setSubject("Hello");
        msg.setText("What's up?");
        Transport.send(msg);
        response.getWriter().println("Message sent");
    }

    catch(Exception e)
    {
        System.out.println(e);
    }

}
}

What do I've to do to make the connection?

Was it helpful?

Solution

Well, you haven't set up any authentication as far as I can tell. You've grabbed the username and the password from the request (I do hope this is over HTTPS) but you haven't used it anywhere.

I strongly recommend that you try to get this working in a console app which will be much easier to debug than a servlet, then put it into a servlet environment.

OTHER TIPS

Yes, you haven't authenticated anything. The url you'll want to authenticate with GMail is this one.

https://www.google.com/accounts/ServiceLoginAuth?service=mail&Email=YOUREMAIL&Passwd=URLENCODEDPASSWORD

You'll want to substitute appropriate values for YOUREMAIL and URLENCODEDPASSWORD. You can encode your password with a simple

URLEncoder.encode("password");

Please find the solution you need to do. 1. Instead of using Transport.send() use the following line of code

Transport tp = session.getTransport("smtp");
  tp.connect("smtp.gmail.com", 465, userName, password);
  tp.sendMessage(msg, msg.getAllRecipients());

Your Program should work then.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top