您的位置:首页 > 其它

利用J2ME和servlet技术实现手机发送邮件

2010-10-01 01:59 756 查看
这两天一直在研究手机端如何利用java技术来发送邮件,之前学习了在电脑端利用Java发送邮件的原理,那么手机端能否像电脑端那样,直接把邮件发给邮箱服务器呢?听说现在MIDlet2.0也支持这样发邮件,但是具体如何实现没有深究。我想,能否通过手机把参数和内容发送给电脑端,然后让电脑帮助我们发邮件呢?经过搜索资料,发现答案是肯定的。这里就利用到servlet技术:手机作为客户端,电脑作为服务端(其实就是通常说的代理)。

servlet 的配置是最令人头疼的,我的大部分时间都花在这里。

以下是步骤:

1.在tomcat的webapps目录下建mail文件夹,再里面建WEB-INF文件夹,然后再WEB-INF里面建classes和lib文件夹,一个web.xml文件,classes里放的是编译后的servlet类(编译时要把tomcat的servlet-api.jar放到jre的ext文件夹中),lib放的是要用到的jar文件,这里我们要把mail.jar(J2EE的一个邮件的jar文件)放到里面去,否则访问servlet时会出错。web.xml内容如下:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!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>

<!-- MailServlet definition -->
<servlet>
<servlet-name>MailServlet </servlet-name>
<servlet-class>com.j2medev.mail.MailServlet</servlet-class>
</servlet>

<!-- MailServlet mapping -->
<servlet-mapping>
<servlet-name>MailServlet</servlet-name>
<url-pattern>/MailServlet</url-pattern>
</servlet-mapping>

</web-app>

然后通过http://localhost:6060/mail/MailServlet访问servlet,成功通过手机发送邮件。

发邮件只是很小的一部分,至于如何收取邮件,在电脑端建立数据库存储邮件,监听有无新邮件,这些都是以后的事了。

以下是测试代码:

servlet:

package com.j2medev.mail;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage.RecipientType;
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 {
response.setContentType("text/html;charset=GB2312");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<title>");
out.println("fuck java mail!");
out.println("</title>");
out.println("</body>");
out.println("</html>");
DataInputStream dis = new DataInputStream(request.getInputStream());
String send = dis.readUTF();
String from="792553306@qq.com";
//String send ="792553306@qq.com";
String subject = dis.readUTF();
//String subject ="subject";
String content = dis.readUTF();
//String content="content";
try {
Properties props = new Properties();
// Setup mail server
props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props);
// Define message
MimeMessage message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress(from));
// message.setRecipients(Message.RecipientType.TO,send);
// Set the to address
message.setRecipient(RecipientType.TO, new InternetAddress(send));
message.setRecipients(RecipientType.TO, InternetAddress.parse(from));
// Set the subject
message.setSubject(subject);
// Set the content
message.setText(content);

//	message.setFrom(from);// 设置发件人
//	InternetAddress to = new InternetAddress(tto);
//	message.setRecipient(Message.RecipientType.TO, to);// 设置收件人
//	message.setRecipients(RecipientType.TO, InternetAddress.parse(afrom));// 如果是多个收信人
//	message.setSubject(ttitle);// 设置主题
//	message.setText(tcontent);// 设置信件内容

BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
mdp.setContent(content, "text/html;charset=gb2312"); // 给BodyPart对象设置内容和格式/编码方式
Multipart test = new MimeMultipart();// 新建一个MimeMultipart对象用来存放对象
test.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中
message.setContent(test);// 把mm作为消息对象的内容
// 发送邮件
message.saveChanges();// 存储邮件信息
Transport transport = session.getTransport("smtp");
transport.connect("smtp.qq.com", from, "51332lin");// 以smtp方式登录邮箱
// 注意这一步需要你的用户名和密码,务必正确,才能正常发送
transport.sendMessage(message, message.getAllRecipients());// 发送邮件,其中第二个参数是所有已设好的收件人地址
transport.close();
// Send message

} catch (Exception e) {
e.printStackTrace();
}
}
}


手机端,4个类 MailClient为主类 ContentForm为内容窗口 MainForm为主窗口 Message为一般类

package 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", "content", 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:6060/mail/MailServlet");
httpConn.setRequestMethod("POST");
//if(httpConn.getResponseCode()==HttpConnection.HTTP_OK)
//System.out.println("OK"+httpConn.getResponseCode()+"/n");
dos = new DataOutputStream(httpConn.openOutputStream());
dos.writeUTF(midlet.getMessage().getTo());
dos.writeUTF(midlet.getMessage().getSubject());
dos.writeUTF(midlet.getMessage().getContent());
dos.flush();
dos.close();// 不注释这里有错误显示
httpConn.close();
System.out.println("end of sending mail");
}
catch(IOException e)
{}
}
}
//////////////////////////////////////////////////////

package 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)
{
}
}
}
}

///////////////////////////////////////////////////

/*
* Created on 2004-12-8
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package mail;
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:","792553306@qq.com", 25, TextField.ANY);
subField = new TextField("Subject:", "subject", 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 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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: