用J2ME完成容易電子郵件發(fā)送技巧
發(fā)表時間:2024-01-01 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]作者:mingjava 文章來源:http://www.j2medev.com/Article/ShowArticle.asp?ArticleID=141在GCF中并沒有提供給我們能夠發(fā)送電子郵件的API,J2ME的可選包也沒有提供相關(guān)的功能。那么我們能用J2ME實現(xiàn)發(fā)送電子郵件功能嘛?答案是肯...
作者:mingjava 文章來源:http://www.j2medev.com/Article/ShowArticle.asp?ArticleID=141
在GCF中并沒有提供給我們能夠發(fā)送電子郵件的API,J2ME的可選包也沒有提供相關(guān)的功能。那么我們能用J2ME實現(xiàn)發(fā)送電子郵件功能嘛?答案是肯定的。本文將主要講述如何在J2ME中實現(xiàn)發(fā)送電子郵件的功能。
這里一個非常重要的思想就是代理。我們知道GCF提供給我們進(jìn)行聯(lián)網(wǎng)的能力了,比如通過Http聯(lián)網(wǎng)。在MIDP2.0中甚至提供了socket聯(lián)網(wǎng)的API。那么我們可以通過他們連接服務(wù)器端的程序比如servlet,然后servlet可以通過JavaMail提供的接口發(fā)送郵件。那么我們需要做的只是通過Http協(xié)議或者其他協(xié)議把郵件的標(biāo)題、內(nèi)容、收件人等發(fā)送給servlet。就是這個簡單的思想?yún)s是非常靈活非常有用。
首先我們構(gòu)造一個Message類來代表發(fā)送的消息。它包括主題、收件人和內(nèi)容三個字段。
package com.j2medev.mail;
public class Message
{
private String to;
private String subject;
private String content;
public Message()
{
}
public Message(String to, String subject, String content)
{
this.to = to;
this.subject = subject;
this.content = content;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
public String getSubject()
{
return subject;
}
public void setSubject(String subject)
{
this.subject = subject;
}
public String getTo()
{
return to;
}
public void setTo(String to)
{
this.to = to;
}
public String toString()
{
return to+subject+content;
}
}
在用戶界面的設(shè)計上,我們需要兩個界面。一個讓用戶輸入收件人和主題,另一個用于收集用戶輸入的內(nèi)容。由于TextBox要獨占一個屏幕的,因此我們不能把他們放在一起。
/*
* Created on 2004-12-8
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.j2medev.mail;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
* @author P2800
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class MainForm extends Form implements CommandListener
{
private MailClient midlet;
private TextField toField;
private TextField subField;
private boolean first = true;
public static final Command nextCommand = new Command("NEXT", Command.OK, 1);
public MainForm(MailClient midlet, String arg0)
{
super(arg0);
this.midlet = midlet;
if(first)
{
first = false;
init();
}
}
public void init()
{
toField = new TextField("To:", null, 25, TextField.ANY);
subField = new TextField("Subject:", null, 30, TextField.ANY);
this.append(toField);
this.append(subField);
this.addCommand(nextCommand);
this.setCommandListener(this);
}
public void commandAction(Command cmd,Displayable disp)
{
if(cmd == nextCommand)
{
String to = toField.getString();
String subject = subField.getString();
if(to == "" && subject == "")
{
midlet.displayAlert("Null to or sub",AlertType.WARNING,this);
}
else
{
midlet.getMessage().setTo(to);
midlet.getMessage().setSubject(subject);
midlet.getDisplay().setCurrent(midlet.getContentForm());
}
}
}
}
package com.j2medev.mail;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
public class ContentForm extends TextBox implements CommandListener
{
private MailClient midlet;
private boolean first = true;
public static final Command sendCommand = new Command("SEND", Command.ITEM,
1);
public ContentForm(String arg0, String arg1, int arg2, int arg3,
MailClient midlet)
{
super(arg0, arg1, arg2, arg3);
this.midlet = midlet;
if (first)
{
first = false;
init();
}
}
public void init()
{
this.addCommand(sendCommand);
this.setCommandListener(this);
}
public void commandAction(Command cmd, Displayable disp)
{
if (cmd == sendCommand)
{
String content = this.getString();
midlet.getMessage().setContent(content);
System.out.println(midlet.getMessage());
try
{
synchronized (midlet)
{
midlet.notify();
}
} catch (Exception e)
{
}
}
}
}
最后我們完成MIDlet,在其中包括聯(lián)網(wǎng)的程序代碼,由于本站已經(jīng)提供了很多關(guān)于J2ME聯(lián)網(wǎng)的介紹,因此這里不再進(jìn)行更多的解釋。
package com.j2medev.mail;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
public class MailClient extends MIDlet
{
private MainForm mainForm;
private ContentForm contentForm;
private Display display;
private Message message;
public Message getMessage()
{
return message;
}
public void setMessage(Message message)
{
this.message = message;
}
public void displayAlert(String text, AlertType type, Displayable disp)
{
Alert alert = new Alert("Application Error");
alert.setString(text);
alert.setType(type);
alert.setTimeout(2000);
display.setCurrent(alert, disp);
}
public ContentForm getContentForm()
{
return contentForm;
}
public Display getDisplay()
{
return display;
}
public MainForm getMainForm()
{
return mainForm;
}
public void initMIDlet()
{
MailThread t = new MailThread(this);
t.start();
message = new Message();
display = Display.getDisplay(this);
mainForm = new MainForm(this, "Simple Mail Client");
contentForm = new ContentForm("Content", null, 150, TextField.ANY, this);
display.setCurrent(mainForm);
}
protected void startApp() throws MIDletStateChangeException
{
initMIDlet();
}
protected void pauseApp()
{
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException
{
}
}
class MailThread extends Thread
{
private MailClient midlet;
public MailThread(MailClient midlet)
{
this.midlet = midlet;
}
public void run()
{
synchronized(midlet)
{
try
{
midlet.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("connecting to server.....");
HttpConnection httpConn = null;
DataOutputStream dos = null;
try
{
httpConn = (HttpConnection)Connector.open("http://localhost:8088/mail/maildo");
httpConn.setRequestMethod("POST");
dos = new DataOutputStream(httpConn.openOutputStream());
dos.writeUTF(midlet.getMessage().getTo());
dos.writeUTF(midlet.getMessage().getSubject());
dos.writeUTF(midlet.getMessage().getContent());
dos.close();
httpConn.close();
System.out.println("end of sending mail");
}
catch(IOException e)
{}
}}
在服務(wù)器端,我們要完成自己的servlet。他的任務(wù)比較簡單就是接受客戶端的數(shù)據(jù)然后通過JavaMail發(fā)送到指定的收件人那里。如果您對JavaMail還不熟悉請參考如下文章。這里直接給出servlet代碼。
使用JavaMail實現(xiàn)收發(fā)電子郵件功能
使用Servlet發(fā)送電子郵件
package com.j2medev.servletmail;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
import java.net.*;
public class MailServlet extends HttpServlet
{
private static String host;
private static String from;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
host = config.getInitParameter("host");
from = config.getInitParameter("from");
System.out.println(host + from);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
DataInputStream dis = new DataInputStream(request.getInputStream());
String send = dis.readUTF();
String subject = dis.readUTF();
String content = dis.readUTF();
try
{
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// Set the to address
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
send));
// Set the subject
message.setSubject(subject);
// Set the content
message.setText(content);
// Send message
Transport.send(message);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ServletMail</servlet-name>
<servlet-class>com.j2medev.servletmail.MailServlet</servlet-class>
<init-param>
<param-name>host</param-name>
<param-value>smtp.263.net</param-value>
</init-param>
<init-param>
<param-name>from</param-name>
<param-value>eric.zhan@263.net</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletMail</servlet-name>
<url-pattern>/maildo</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
總結(jié):本文更多要介紹的其實還是這個代理的思想,利用所學(xué)的知識靈活應(yīng)用。不要局限于J2ME提供給你的API。文章中實現(xiàn)的客戶端服務(wù)器都比較簡單,也不夠友好,如果感興趣可以稍微修飾一下,對提高能力還是有幫助的。在MIDP中只是提供了RMS作為持久存儲用,因此實現(xiàn)接受存儲郵件不是很方便。如果手機(jī)支持FileConnection的話可以編寫一個接受郵件的客戶端。