25 mei 2009

Sending email with PHP at GAE

Currently sending email from PHP scripts on Google App Engine is not working. Most likely this will be possible in the future again when the nice folks of Caucho adjust Quercus to the GAE sandbox.

This article shows how to use a small Java program for sending email from PHP at Google App Engine.

With using a small java source you can send email from your PHP scripts at GAE with below line:
 gaeMail('me@gmail,com', 'someone@inter.net', 'Subject', 'Hi, how are you?');
First add resin.jar to the build path for your GAE project in Eclipse with properties -> Java build path -> Libraries

Below the Java code, save it as src/gae/email.java in your GAE project in Eclipse.
package gae;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.caucho.quercus.module.AbstractQuercusModule;

public class email extends AbstractQuercusModule {

public void gaeMail(String from, String to, String subject, String body)

throws java.io.IOException {

Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);

try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(body);
Transport.send(msg);
} catch (AddressException e) {
// ...
} catch (MessagingException e) {
// ...
}

}

}
To make Quercus aware of your new email fuction, add below line to the file src/META-INF/services/com.caucho.quercus.QuercusModule (create this file if it not yet exists)
 gae.email
See quercus: java and php integration for more information how to write your own PHP functions with Java for Quercus PHP on GAE.

3 opmerkingen:

desktopguy zei

Brilliant - I am trying to integrate this with my GAE test site.
Only question would be how would you create an array to pass values from a contact form onto the the php script?

Anoniem zei

Hello,

I have tried to use this method. But after I update to GAE and access the php page it says the function is unknown. Did you get this to work?
I'm using resin 4.0.29

HGJ zei

@ken: Are you sure this work around is still needed? This blog posting from me is from 2009 ! I assume it must now be possible with the default Quercus implementation.