Enviando e-mail de dispositivos J2ME

Quando você envia um e-mail, você conecta um usuário com um servidor que suporta o Simple Mail Transfer Protocol (smtp). Um MIDLet conecta com o servidor através do protocolo http. Para enviar um e-mail, é necessário codificiar um servlet hospedado em um web server. Midlet envia e recebe dados do servlet.

O exemplo abaixo envia um e-mail a partir de dispositivos J2ME:

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.PrintStream;


public class SendMail extends MIDlet implements CommandListener {

    private String MAIL_SERVER_URL = 
            "http://localhost:8080/examples/servlet/SendMailServlet?";
    Display display = null;
    List dmenu = null;
    TextBox input = null;
    TextBox to =null;
    TextBox 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 + "u=" + user;
    
    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);
        else if (c == backCommand) {
            displayMenu();
        else if (c == submitCommand) {
            user = input.getString();
            doLogin(user);
            
        else if (c == okCommand) {
            t = new SendThread(input.getString(),to.getString(),
                    msg.getString());
            
            showAlert(t.getResponseMessage());
        else if (d == dmenu) {
            handleMainMenu();
        else
            loginUser();
    }
    
    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);
        dmenu.setCommandListener(this);
        display.setCurrent(dmenu);
        status = 0;
    }
    
    /* Este método pergunta ao usuário seu e-mail e sua senha */
    private void loginUser() {
        input = new TextBox(
            "Digite Login/Password (Separado pela /) :"""25
            TextField.ANY);
        
        input.addCommand(submitCommand);
        input.addCommand(backCommand);
        input.setCommandListener(this);
        display.setCurrent(input);
    }
    
    /* Este método executa o inicio de uma sessão */
    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("UsuarioInvalido") >= 0) {
                user = null;
                showAlert("Usuario e senha errados");
            else {
                input = null;
                dmenu = null;
                displayMenu();
            }
        else
            showAlert(err); // Necessário para a página de erro
    }
    
    private void showAlert(String err) {
        Alert a = new Alert("");
        a.setString(err);
        a.setTimeout(Alert.FOREVER);
        display.setCurrent(a);
    }
    
    private void handleMainMenu() {
        int index = dmenu.getSelectedIndex();
        switch(index) {
            case :
                if (user != null) {
                    sendeMail();
                    break;
                }
            case :
                status = 1;
                loginUser();
                break;
        }
    }
    
    /* Este método permite que o usuário cria a mensagem do e-mail*/
    private void sendeMail() {
        List menu = new List("Enviar mensagem");
        to = new TextBox("Para :"""50, TextField.ANY);
        msg = new TextBox("Mensagem :"""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 user;
        String pwd;
        String to;
        String msg;
        
        public SendThread(String user,String to,String msg) {
            int j user.indexOf('/');
            if (j > 0) {
                user = user.substring(0,j);
                pwd = user.substring(j+1);
                to = to;
                msg = msg;
            }
        }
        
        /*Este método ob´tem a resposta depois do e-mail ser enviado*/
        public String getResponseMessage() {
            return responseMessage;
        }
        
        /* Este método  envia um POST request para o servlet com os parêmtros

           necessários*/
        public void run() {
            HttpConnection hc = null;
            OutputStream out = null;
            try {
                hc = (HttpConnection)Connector.open(url);
                hc.setRequestMethod(HttpConnection.POST);
                hc.setRequestProperty("Content-Type""text/plain");
                out = hc.openOutputStream();
                PrintStream pout = new PrintStream(out);
                pout.println(user);
                pout.println(pwd);
                pout.println(mEmail);
                pout.println(mMessage);
                
                InputStream in = hc.openInputStream();
                int length = (int)hc.getLength();
                if (length == -1) length = 255;
                byte[] raw = new byte[length];
                in.read(raw);
                String s = new String(raw);
                String codeString = s.substring(04).trim();
                responseMessage = s.substring(4).trim();
            finally {
                if (hc != null) hc.close();
                if (out != null) out.close();
            }
        }
    }
}

/*Servlet para enviar o e-mail*/
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 = "SeuServidor.com";
        mDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    }
    
    public void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, 
            IOException {
        
        BufferedReader in = request.getReader();
        String user = in.readLine();
        String pwd = in.readLine();
        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();
    }
    
    /* Este método cria a mensagem e envia para o servidor*/
    private void sendMail(String server, String user, 
            String pwd, String address, String content) throws Exception {
        
        Properties p = new Properties();
        p.put("mail.smtp.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);
        String now = mDateFormat.format(new java.util.Date());
        m.setSubject("Mail from [" + from + "]");
        m.setText(content.toString());
        Transport.send(m);
    }
 
}