Sending Email from J2ME devices

本文介绍了一种在J2ME设备上实现邮件发送的方法。通过使用Midlet与部署在Web服务器上的Servlet交互,实现了从输入收件人到发送邮件的全过程。此方案利用HTTP协议而非SMTP,提供了一个轻量级的邮件发送解决方案。

When you send mail, you connect to a server that supports the Simple Mail Transfer Protocol (SMTP). A MIDLet connects to the server through HTTP protocol interface. Send Email facility is coded in a servlet hosted on web server. Midlet send and recieve data through servlet.

Example below sends an email from J2ME devices.

/*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 :
                if (user != null) {
                    sendeMail();
                    break;
                }
            case :
                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 == -1length = 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 != nullhc.close();
                if (out != nullout.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 responsethrows 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 contentthrows 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);
    }
    
}
 
本课题设计了一种利用Matlab平台开发的植物叶片健康状态识别方案,重点融合了色彩与纹理双重特征以实现对叶片病害的自动化判别。该系统构建了直观的图形操作界面,便于用户提交叶片影像并快速获得分析结论。Matlab作为具备高效数值计算与数据处理能力的工具,在图像分析与模式分类领域应用广泛,本项目正是借助其功能解决农业病害监测的实际问题。 在色彩特征分析方面,叶片影像的颜色分布常与其生理状态密切相关。通常,健康的叶片呈现绿色,而出现黄化、褐变等异常色彩往往指示病害或虫害的发生。Matlab提供了一系列图像处理函数,例如可通过色彩空间转换与直方图统计来量化颜色属性。通过计算各颜色通道的统计参数(如均值、标准差及主成分等),能够提取具有判别力的色彩特征,从而为不同病害类别的区分提供依据。 纹理特征则用于描述叶片表面的微观结构与形态变化,如病斑、皱缩或裂纹等。Matlab中的灰度共生矩阵计算函数可用于提取对比度、均匀性、相关性等纹理指标。此外,局部二值模式与Gabor滤波等方法也能从多尺度刻画纹理细节,进一步增强病害识别的鲁棒性。 系统的人机交互界面基于Matlab的图形用户界面开发环境实现。用户可通过该界面上传待检图像,系统将自动执行图像预处理、特征抽取与分类判断。采用的分类模型包括支持向量机、决策树等机器学习方法,通过对已标注样本的训练,模型能够依据新图像的特征向量预测其所属的病害类别。 此类课题设计有助于深化对Matlab编程、图像处理技术与模式识别原理的理解。通过完整实现从特征提取到分类决策的流程,学生能够将理论知识与实际应用相结合,提升解决复杂工程问题的能力。总体而言,该叶片病害检测系统涵盖了图像分析、特征融合、分类算法及界面开发等多个技术环节,为学习与掌握基于Matlab的智能检测技术提供了综合性实践案例。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
### 回答1: 可以使用 Python 的 smtplib 模块来发送电子邮件。首先,需要准备好要发送的电子邮件的内容,包括发件人地址、收件人地址、主题和正文。然后,使用 smtplib 模块的 SMTP 类来连接到 SMTP 服务器,并使用 login() 方法登录。接着,使用 sendmail() 方法来发送电子邮件。最后,使用 quit() 方法来断开与 SMTP 服务器的连接。 例如,下面是一段示例代码,展示了如何使用 Python 发送一封简单的电子邮件: ```python import smtplib # 要发送的电子邮件内容 from_addr = 'sender@example.com' to_addr = 'receiver@example.com' subject = 'Test Email' body = 'This is a test email sent from Python.' # 连接到 SMTP 服务器 smtp_server = smtplib.SMTP('smtp.example.com') # 登录到 SMTP 服务器 smtp_server.login('username', 'password') # 构造电子邮件 msg = f'Subject: {subject}\n\n{body}' # 发送电子邮件 smtp_server.sendmail(from_addr, to_addr, msg) # 断开与 SMTP 服务器的连接 smtp_server.quit() ``` 注意,在上面的代码中,需要替换 `sender@example.com` 和 `receiver@example.com` 为实际的发件人地址和收件人地址,并替换 `smtp.example.com` 为实际的 SMTP 服务器地址。此外,需要替换 `username` 和 `password` 为登录 SMTP 服务器的用 ### 回答2: 使用Python发送电子邮件,你可以使用SMTP(简单邮件传输协议)库。 首先,你需要导入smtplib库,以便与SMTP服务器进行通信。然后,创建一个SMTP对象,并登录到你的电子邮件帐户。你需要提供SMTP服务器的主机名和端口号,以及你的电子邮件地址和密码。 接下来,你可以通过调用sendmail()方法来发送邮件。你需要提供发件人,收件人和邮件内容。邮件内容可以通过构建一个MIMEText对象来实现。 以下是一个简单的示例代码,演示如何向一个收件人发送电子邮件: ```python import smtplib from email.mime.text import MIMEText def send_email(): sender = 'example@example.com' receiver = 'example2@example.com' subject = 'Hello from Python' body = 'This is a test email.' msg = MIMEText(body) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver smtp_server = 'smtp.example.com' smtp_port = 587 username = 'your_username' password = 'your_password' server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(username, password) server.sendmail(sender, receiver, msg.as_string()) server.quit() send_email() ``` 在上面的示例中,你需要将示例电子邮件地址,SMTP服务器和登录凭据替换为你自己的信息。 这只是一个简单的示例,你可以根据自己的需求进行进一步的定制,比如添加附件、使用HTML格式的邮件等。 总之,使用Python发送电子邮件是非常简单的,只需要使用Python的smtplib库和MIMEText对象即可实现。 ### 回答3: 使用Python发送电子邮件非常简便和方便。下面是一个基本的步骤。 首先,需要导入smtplib和email模块,分别用于发送邮件和构造邮件。可以使用以下代码导入这些模块: ``` import smtplib from email.mime.text import MIMEText ``` 然后,需要配置SMTP服务器的信息,包括SMTP服务器地址、端口号和认证信息。例如,如果使用Gmail作为SMTP服务器,可以使用以下代码进行配置: ``` smtp_server = 'smtp.gmail.com' smtp_port = 587 username = 'your_email@gmail.com' password = 'your_password' ``` 接下来,可以构造邮件内容。例如,可以使用MIMEText对象创建一个简单的纯文本邮件: ``` message = MIMEText('This is the email content.', 'plain') message['From'] = 'sender@example.com' message['To'] = 'receiver@example.com' message['Subject'] = 'Email Subject' ``` 如果要发送HTML格式的邮件,可以将'MIMEText'改为'MIMEText(html_content, 'html')',其中'html_content'是包含HTML内容的字符串。 最后,使用smtplib模块发送邮件。可以使用以下代码发送邮件: ``` with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(username, password) server.send_message(message) ``` 在这个例子中,首先使用starttls()方法启用TLS加密连接,然后使用login()方法进行身份验证,并最后使用send_message()方法发送邮件。 以上就是使用Python发送电子邮件的基本步骤。根据需要,还可以添加更多的功能,例如添加附件或发送多个收件人。参考Python文档以了解更多细节和选项。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值