File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes how to send email from j2me using Servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Reply locked New topic
Author

how to send email from j2me using Servlets

firstName SecondName
Greenhorn

Joined: Mar 20, 2009
Posts: 15
hi,
I want to send an email using servlets.
I had tried some of the example codes from internet but didn't get any success.
i am j2me person and new in Servlets .
any suggestions please!
Thanks in advance
bhagya hari
Greenhorn

Joined: Oct 15, 2008
Posts: 5
Please post what you have tried and the problem you have faced while running the code.

It will be helpful to fix the problems in your code.

firstName SecondName
Greenhorn

Joined: Mar 20, 2009
Posts: 15
Here is the code which i got from internet but it is not sending email!
This is my servlet code

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

public class SendMailServlet extends HttpServlet {
private String mMailServer;
private DateFormat mDateFormat;

public void init() {
mMailServer = "localhost";
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

String user="user";
String pwd="pass";

BufferedReader in = request.getReader();

String address = in.readLine();

StringBuffer content = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
content.append(line);
content.append('\n');
}

String message = "100 ok";

try {
sendMail(mMailServer,user,pwd, address, content.toString());
} catch (Throwable t) {
message = "200 " + t.toString();
}
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
out.flush();
}

/* This method form Mail and send to server*/
private void sendMail(String server, String user,
String pwd, String address, String content) throws Exception {

Properties p = new Properties();
p.put("local host", server);
Session s = Session.getDefaultInstance(p, null);
InternetAddress from = new InternetAddress(user);
InternetAddress to = new InternetAddress(address);
MimeMessage m = new MimeMessage(s);
m.setFrom(from);
m.addRecipient(Message.RecipientType.TO, to);

m.setSubject("Mail from [" + from + "]");
m.setText(content.toString());
Transport.send(m);
}

}
This is my j2me side code

import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.io.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;


public class SendMail extends MIDlet implements CommandListener {

private String MAIL_SERVER_URL =
"http://localhost:8090/SendMailServlet";
Display display = null;
List dmenu = null;
TextBox input = null;
TextField to =null;
TextField msg =null;
String user = null;
int status =0;
Command backCommand = new Command("Back", Command.BACK, 0);
Command submitCommand = new Command("Submit", Command.OK, 2);
Command exitCommand = new Command("Exit", Command.STOP, 3);
Command okCommand = new Command("OK", Command.OK, 0);
String url = MAIL_SERVER_URL ;



public SendMail() { }

public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
displayMenu();
}

public void pauseApp() { }

public void destroyApp(boolean unconditional) {
notifyDestroyed();
}

public void commandAction(Command c, Displayable d) {
if(c == exitCommand ) {
destroyApp(true);
}
if (c == backCommand) {
displayMenu();
}
if (c == submitCommand) {
user = input.getString();
doLogin(user);
}
if (c == okCommand) {
SendThread t = new SendThread(to.getString(),msg.getString());


showAlert(t.getResponseMessage());

} else if (d == dmenu) {
handleMainMenu();
}
}

private void displayMenu() {
dmenu = new List("Send Email", Choice.IMPLICIT);
if (user == null)
dmenu.append("Login", null);
else
dmenu.append("Logout", null);
dmenu.append("Send Mail", null);
dmenu.addCommand(exitCommand);
display.setCurrent(dmenu);
dmenu.setCommandListener(this);

status = 0;
}

/* This method ask user for his email id and password*/

/* This method perform login */
private void doLogin(String user) {
StreamConnection c = null;
InputStream is=null;
StringBuffer sb = null;
String err = null;

try {
c = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
} catch(Exception ex){ err = ex.getMessage(); } finally {
try {
if(is!= null) {is.close(); }
if(c != null) {c.close(); }
} catch(Exception exp) { err = exp.getMessage(); }
}
if (err == null) {
user = sb.toString();

if (user.indexOf("INVALIDUSR") >= 0) {
user = null;
showAlert("Invalid User Name and Password");
} else {
input = null;
dmenu = null;
displayMenu();
}
} else
showAlert(err); // Need to Show Error Page
}

private void showAlert(String err) {
Alert a = new Alert("Alert");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}

private void handleMainMenu() {
int index = dmenu.getSelectedIndex();
switch(index) {
case 0 :

status = 1;
//loginUser();
break;

case 1 :

sendeMail();
break;

}
}

/* This method ask user to compose the message*/
private void sendeMail() {
Form menu = new Form("Send Message");
to = new TextField("Enter Reciepent :", "", 50, TextField.EMAILADDR);
msg = new TextField("Enter Message :", "", 250, TextField.ANY);
menu.append(to);
menu.append(msg);
menu.addCommand(okCommand);
menu.addCommand(exitCommand);
menu.setCommandListener(this);
display.setCurrent(menu);
}

public class SendThread implements Runnable {

String to;
String msg;
private String responseMessage="nothing new";


public SendThread(String user_to,String user_msg) {


this.to = user_to;
this.msg = user_msg;

}

/*This method gets the response after sending the mail*/
public String getResponseMessage() {
return responseMessage;
}

/* This method send POST request to servlet with necessary params*/
public void run() {

System.out.println("Success");
HttpConnection hc = null;
OutputStream out = null;
try {
try {
hc = (HttpConnection) Connector.open(url);

hc.setRequestMethod(HttpConnection.POST);

hc.setRequestProperty("Content-Type", "text/plain");

out = hc.openOutputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
PrintStream pout = new PrintStream(out);

pout.println(to);
pout.println(msg);

InputStream in = null;
try {
in = hc.openInputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
int length = (int)hc.getLength();
if (length == -1) length = 255;
byte[] raw = new byte[length];
try {
in.read(raw);
} catch (IOException ex) {
ex.printStackTrace();
}
String s = new String(raw);
String codeString = s.substring(0, 4).trim();
responseMessage = s.substring(4).trim();
} finally {
if (hc != null) try {
hc.close();

if (out != null)
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
firstName SecondName
Greenhorn

Joined: Mar 20, 2009
Posts: 15
thanks for your time,

I got solution now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to send email from j2me using Servlets