Google

Monday, January 19, 2009

J2ME SMTP / POP3 - This Code Does Not Work

This code for sending and receiving emails as shown below taken from

http://www.experts-exchange.com/Networking/Wireless/Q_21094744.html

does not work. The reason is because you did not wait for server to
reply before sending the next command.

See my later blog for correct version.


public void sendEmail() {

try {
sc = (SocketConnection) Connector.open("socket://"
+ smtpServerAdress + ":25");
is = sc.openInputStream();
os = sc.openOutputStream();
sb = new StringBuffer();

// Send SMTP-Commands
os.write(("HELO" + domain + "\r\n").getBytes());
os.write(("MAIL FROM: "+ from_emailAdress +"\r\n").getBytes());
os.write(("RCPT TO: "+ to_emailAdress + "\r\n").getBytes());
os.write("DATA\r\n".getByt
es());
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: MIAM TEST\r\n").getBytes());
os.write(("TESTMESSAGE FROM MIAM \r\n").getBytes());
os.write(".\r\n".getBytes(
));
os.write("QUIT\r\n".getByt
es());

int c = 0;

// DOESN'T LEAVE LOOP
while ( (c = is.read() ) != -1) {
sb.append( (char)c);

}

System.out.println(sb.toSt
ring());
}
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 getEmail() {

try {
sc = (SocketConnection) Connector.open("socket://"
+ popServerAdress + ":110");
is = sc.openInputStream();
os = sc.openOutputStream();
sb = new StringBuffer();

int ch = 0;
os.write( ("USER " + userName + "\r\n").getBytes());
os.write( ("PASS " + userPass + "\r\n").getBytes());
os.write( ("LIST" + "\r\n").getBytes());
os.write( ("RETR 1" + "\r\n").getBytes());
os.write("QUIT\r\n".getByt
es());

while ( (ch = is.read() ) != -1) {
sb.append( (char) ch);
}
System.out.println(sb.toSt
ring());
}

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();
}
}
}