google-app-enginegoogle-api-java-clientapp-engine-patch

Send mail from app engine (anauthorization solution)


In googel app engine, if we are not using OpenID login, we can send mails like its written in API

But I use OpenId Login (using Google mail) and I cant use this.

But I do something like thatL

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "mail@gmail.com", "pass");
                    }
                });



            **Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("mail"));
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mail"));
            message.setSubject("Testing Subject");
            message.setText(msgBody);
            Transport.send(message);

IF I WILL LOG IN AND THEN CALL THAT SERVLET, for instance www.example.appspot.com/mail it works! but if I'm not logged in, it does not work! But I don't understand what happens?!**

java.lang.RuntimeException: javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Illegal Arguments (java.lang.IllegalArgumentException: Unauthorized Sender: Unauthorized sender))
    at test.queue.MailServlet.sendMail(MailServlet.java:208)

at this 208 line I have this:

protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("example@gmail.com","pass");
        }

Solution

  • the address set in the "from" should be present under the Admission -> Permissions for the gae application, and for sending email from this permitted account, no need to specify password in the code.

    "For security purposes, the sender address of a message must be the email address of an administrator for the application or any valid email receiving address for the app (see Receiving Mail). The sender can also be the Google Account email address of the current user who is signed in, if the user's account is a Gmail account or is on a domain managed by Google Apps." - as mentioned here https://developers.google.com/appengine/docs/java/mail/#Java_Sending_mail_with_the_JavaMail_API