[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3619
  • Last Modified:

Sending Email in J2ME

I was wondering the differents ways to send emails in a secure way in j2me without using Java Servlets.
Can someone send me some code ?
0
jonathan_otero
Asked:
jonathan_otero
  • 6
1 Solution
 
keyurkarnikCommented:
For sending mail to the SMTP servver directly, you need to connect to the host - port and send the data to it.

Make sure you have IP enabled, (GPRS)


Here is some sample code :

0
 
keyurkarnikCommented:

String msgstr="";
msgstr=msgstr + "From:name@domain.com\n";
msgstr=msgstr + "To:sendto@domain.com \n";
msgstr=msgstr + "Content-type: text/html;charset=US-ASCII\n";
msgstr=msgstr + "Content-transfer-encoding: 7BIT\n";
msgstr=msgstr + "Subject:Your Subjext\n";
msgstr=msgstr + "CC:ccto@domain.com \n";
msgstr=msgstr + "Content-desciption:Mail message body\n\n\n";
msgstr=msgstr + "Body Of Your Message"

SndMl sndml=new SndMl();
sndml.opensoc();
sndml.sendsoc("helo username",1,"]");
//the next 3 lines are only applicable if you need to log on to the mail server
sndml.sendsoc("AUTH LOGIN",1,"WU6");
sndml.sendsoc("c3RldmVqQHNhc25ldC5jby56aYQ==",1,"mQ6"); //depends if logon is encrypted
sndml.sendsoc("I3N0ZXZdlag==",1,"ful");
sndml.sendsoc("Mail From: name@domain.com",1,"OK");
sndml.sendsoc("Rcpt To: name@domain.com ",1,"Ok");
sndml.sendsoc("Rcpt To: name@domain.com ",1,mailto);
sndml.sendsoc("Rcpt To: name@domain.com",1,ccmailto);
sndml.sendsoc("data",1,".<CRLF>");
msgstr=msgstr + "\n\n";
sndml.sendsoc(msgstr,0,"0");
sndml.sendsoc(".",1,"delivery");
sndml.sendsoc("quit",0,"0");
sndml.closesoc();

public SndMl sndml;

class SndMl
{
SndMl()
{
}

void opensoc()
{
try
{
int osch=0;
String osocstr="";

sc = (SocketConnection)Connector.open(mailsvr);
sc.setSocketOption(SocketConnection.KEEPALIVE, 1);
is = sc.openInputStream();
os = sc.openOutputStream();

}
catch(IllegalArgumentException e)
{
OrderForm.append("ILLEGAL ARG");
}

catch(IOException je)
{
OrderForm.append("ILLEGAL IO");
}
}

void closesoc()
{
try
{
is.close();
os.close();
sc.close();
}
catch(IOException cje)
{
//System.out.print("ILLEGAL CLOSE");
}
}
/*
socmsg=data to send to smtp socket
wt 0= dont wait for reply
wt 1 =wait for reply
sretstr=the string that must be received if a reply is needed
*/
void sendsoc(String socmsg, int wt, String sretstr)
{
int socntr=0;
int sch=0;
int dumcntr=0;
String socstr="";

try
{
socmsg=socmsg + "\r\n";
dumcntr=0;
os.write(socmsg.getBytes());
os.flush();
sch = 0;
socstr="";
if (wt!=0)
{
while(socstr.indexOf(sretstr)==-1)
{
sch = is.read();
Character socc=new Character((char)sch);
if(sch>31 && sch<127)
{
socstr=socstr + socc.toString();
//OrderForm.append(socc.toString());
}
}
}
while(dumcntr<17000)
{
dumcntr++;
}
Form.append(".");
}

catch(IllegalArgumentException e)
{
OrderForm.append("ILLEGAL ARG");
}

catch(IOException je)
{
OrderForm.append("ILLEGAL IO");
}
}
}
}
0
 
keyurkarnikCommented:
make sure you set the parameteers correctly in the message string.
See what might be missing and improvise
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
keyurkarnikCommented:
Sending via servlet is more easier though - just in case :)


/*Midlet running on device*/
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;
    }
   
    /* This method ask user for his email id and password*/
    private void loginUser() {
        input = new TextBox(
            "Enter Login Name/Password (Seperate by /) :", "", 25,
            TextField.ANY);
       
        input.addCommand(submitCommand);
        input.addCommand(backCommand);
        input.setCommandListener(this);
        display.setCurrent(input);
    }
   
    /* 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("");
        a.setString(err);
        a.setTimeout(Alert.FOREVER);
        display.setCurrent(a);
    }
   
    private void handleMainMenu() {
        int index = dmenu.getSelectedIndex();
        switch(index) {
            case 0 :
                if (user != null) {
                    sendeMail();
                    break;
                }
            case 1 :
                status = 1;
                loginUser();
                break;
        }
    }
   
    /* This method ask user to compose the message*/
    private void sendeMail() {
        List menu = new List("Send Message");
        to = new TextBox("Enter Reciepent :", "", 50, TextField.ANY);
        msg = new TextBox("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 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;
            }
        }
       
        /*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() {
            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(0, 4).trim();
                responseMessage = s.substring(4).trim();
            } finally {
                if (hc != null) hc.close();
                if (out != null) out.close();
            }
        }
    }
}

/*Servlet to send email*/
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 = "yourserver.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();
    }
   
    /* 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("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);
    }
   
}
0
 
keyurkarnikCommented:
Also check the code here :

http://developers.sun.com/mobility/midp/articles/socketRMI/

It has examples of both ways
0
 
keyurkarnikCommented:
import java.io.*;
import java.net.*;
import java.util.Date;

public class EmailSender {

  public EmailSender() {
  }

  public void send(String from, String to, String subject, String msg) {
     Socket smtpSocket = null;
     DataOutputStream os = null;
     DataInputStream is = null;

     try {
       smtpSocket = new Socket("Address for SMTP server", 25);
       os = new DataOutputStream(smtpSocket.getOutputStream());
       is = new DataInputStream(smtpSocket.getInputStream());
     } catch (UnknownHostException e) {
       System.err.println("Don't know about host: hostname");
     } catch (IOException e) {
       System.err.println("Couldn't get I/O for the connection to: hostname");
     }

     if (smtpSocket != null && os != null && is != null) {
      try {
        os.writeBytes("HELO there"+"\r\n");
        os.writeBytes("MAIL FROM: "+ from +"\r\n");
        os.writeBytes("RCPT TO: "+ to + "\r\n");
        os.writeBytes("DATA\r\n");
        os.writeBytes("Date: "+ new Date() + "\r\n"); // stamp the msg with date
        os.writeBytes("From: "+from+"\r\n");
        os.writeBytes("To: "+to+"\r\n");
        os.writeBytes("Subject: "+subject+"\r\n");
        os.writeBytes(msg+"\r\n"); // message body
        os.writeBytes(".\r\n");
        os.writeBytes("QUIT\r\n");
        // debugging
        String responseLine;
        while ((responseLine = is.readLine()) != null) {
          System.out.println("Server: " + responseLine);
          if (responseLine.indexOf("delivery") != -1) {
             break;
          }
        }

        os.close();
        is.close();
        smtpSocket.close();
      } catch (UnknownHostException e) {
        System.err.println("Trying to connect to unknown host: " + e);
      } catch (IOException e) {
        System.err.println("IOException: " + e);
      }
    }
  }
}
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now