How do I get JButton to send an email? (Java Swing)
Here's the开发者_开发百科 code I have installed at the top of my document:
copied from: 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
and here's the code I have installed in my button's event handler:
private void confirmationYesButtonHandler(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Transport.send(msg);
}
The error message I get from netbeans is:
"cannot find variable msg"
The 2 options NetBeans gives me to "solve" the issue are:
- "Create Field msg in my.planterstatus.PlanterStatusUI"
- "Create Local Variable msg"
I don't know how to fix this. From my extremely limited understanding of Java, it looks like the "msg" variable has been fleshed out at the top of the document, but apparently not.
Help is appreciated!
The scope of the msg
variable you've shown is limited to the try
block it is within.
Here's a page from the "Java Made Easy" tutorial on scope
that appears fairly easy to understand.
msg is declared in the try block and thus is only visible in the try block.
精彩评论