如何在移动设备上通过访问Servlet来发送邮件

本文介绍了一种利用Servlet作为邮件发送适配器的方法,使移动应用能够通过HTTP协议发送邮件。具体实现包括MIDlet客户端与Servlet服务器端的交互流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传统的,当我们发送邮件的时候,邮件客户端软件会连接到支持Simple Mail Transfer Protocol(SMTP)的邮件服务器. 由于在MIDLet中,我们经常使用HTTP协议来和服务器进行数据交换,因此通常就需要一个Servlet来作为邮件发送适配器来实现发送邮件的功能。


发送邮件的代码由Servlet完成,MIDlet仅仅发送采集的数据给Servlet并显示结果

下边的代码实现了如何在移动设备上通过访问Servlet来发送邮件

/*运行在移动设备上的MIDlet*/
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;
    }
   
    /* 采集邮件地址和密码*/
    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);
    }
   
    /* 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); // 显示错误信息
    }
   
    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;
        }
    }
   
    /* 让用户生成一个邮件*/
    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;
            }
        }
       
        /*发送邮件后获得响应结果*/
        public String getResponseMessage() {
            return responseMessage;
        }
       
        /* 发送POST请求给servlet*/
        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*/
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();
    }
   
    /* 构造邮件并发送给邮件服务器*/
    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);
    }
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值