Google

Monday, February 2, 2009

J2ME SMTP Client - This one works

I've modified and corrected the errors in the the earlier
version. The code below works. It sends the message:
'TESTMESSAGE FROM INTI' to your email address.
You need to use nslookup to find the SMTP server
for your email domain first and substitue it in
the appropriate places.


/*
* SMTPClient by Paul Chin
*/
package smtpclient;

import java.io.*;
import java.util.Date;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class SMTPClientMidlet extends MIDlet implements CommandListener, Runnable {

SocketConnection sc;
Display d;
Form f;
Command cmExit, cmSend;
InputStream is = null;
OutputStream os = null;
StringBuffer sb = new StringBuffer();
static final String domain = "intipen.edu.my";
static final String smtpServerAdress = "b.mx.mail.yahoo.com";
static final String from_emailAdress = "justacoder@intipen.edu.my";
static final String to_emailAdress = "javarocks@yahoo.com";
Thread t;

public SMTPClientMidlet() {
cmExit = new Command("Exit", Command.EXIT, 0);
cmSend = new Command("Send", Command.SCREEN, 1);


f = new Form("SMTP Client");


f.addCommand(cmExit);
f.addCommand(cmSend);
f.setCommandListener(this);
}

public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);

t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void sendEmail() {
int ch;
byte[] b = new byte[2046];
try {
sc = (SocketConnection) Connector.open("socket://" + smtpServerAdress + ":25");
is = new DataInputStream(sc.openInputStream());

os = sc.openOutputStream();

is.read(b);
// Send SMTP-Commands
os.write(("HELO " + domain + "\r\n").getBytes());
is.read(b);


os.write(("MAIL FROM: <" + from_emailAdress + ">\r\n").getBytes());
is.read(b);


os.write(("RCPT TO: <" + to_emailAdress + ">\r\n").getBytes());
is.read(b);


os.write("DATA\r\n".getBytes());
is.read(b);

os.write(("Date: " + new Date() + "\r\n").getBytes());
os.write(("From: " + from_emailAdress + "\r\n").getBytes());
os.write(("To: " + to_emailAdress + "\r\n").getBytes());
os.write(("Subject: INTI TEST\r\n").getBytes());
os.write(("\r\n").getBytes());
os.write(("TESTMESSAGE FROM INTI \r\n").getBytes());
os.write(".\r\n".getBytes());
is.read(b);

os.write("QUIT\r\n".getBytes());
is.read(b);

System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}

public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmSend) {
t.start();
}
}

public void run() {
sendEmail();
}
}