如何让JButton发送电子邮件? (Java Swing)

时间:2010-11-29 02:29:52

标签: java email swing jbutton

以下是我在文档顶部安装的代码:

复制自:http://coders-and-programmers-struts.blogspot.com/2009/05/sending-email-using-javamail-e-mailing.html

    package my.planterstatus;

import java.awt.event.ActionEvent;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;

/**
 *
 * @author Kris
 */


public class PlanterStatusUI extends javax.swing.JFrame
   {

    /** Creates new form PlanterStatusUI */
    public PlanterStatusUI() {
        initComponents();
    }

        public String status = new String(); {
        }

public class TestEmail {
// Send a simple, single part, text/plain e-mail
    public void main(String[] args, String status) {
    // SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
    String to = "blah@blahblahblah.com";
    String from = "Planter Status";
    // SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
    String host = "smtp.blahblah.com";
    // Create properties, get Session
    Properties props = new Properties();
    // If using static Transport.send(),
    // need to specify which host to send it to
    props.put("pop.blahblah.net", host);
    // To see what is going on behind the scene
    props.put("mail.debug", "true");
    Session session = Session.getInstance(props);
try {
   // Instantiatee a message
    Message msg = new MimeMessage(session);
    //Set message attributes
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("PS# " + display.getText()+ " is currently " + status);
    msg.setSentDate(new Date());
    // Set message content
    msg.setText("PS# " + display.getText()+ " is currently " + status);
    //Send the message
    Transport.send(msg);
    }
catch (MessagingException mex) {
    // Prints all nested (chained) exceptions as well
    mex.printStackTrace();
    }
}
}//End of class

,这是我在按钮的事件处理程序中安装的代码:

   private void confirmationYesButtonHandler(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        Transport.send(msg);
    }

我从netbeans获得的错误消息是:

“找不到变量msg”

NetBeans让我“解决”这个问题的两个选项是:

  1. “在my.planterstatus.PlanterStatusUI中创建字段消息”
  2. “创建本地变量消息”
  3. 我不知道如何解决这个问题。根据我对Java的极为有限的理解,看起来“msg”变量已经在文档顶部充实,但显然不是。

    非常感谢帮助!

2 个答案:

答案 0 :(得分:1)

您展示的msg变量的范围仅限于它所在的try块。

以下是来自"Java Made Easy" tutorial on scope的页面,看起来相当容易理解。

答案 1 :(得分:0)

msg在try块中声明,因此只在try块中可见。