How do I get JButton to send an email? (Java Swing) - java

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.

Related

Mail sending is failed using java

I have used java mail API for sending mail in my application using java and web driver.My requirement is to send a mail whenever a link/url is down.Even though mail is send when i give url incorrectly ,but at the same time if a url is not loading due any other issue (page not found), found that mail is not getting send.
public void SendMail(String url,String str)
{
try
{
Sheet mailsheet = w.getSheet("mail");
String from = mailsheet.getCell(0,1).getContents().toString().trim();
String toEmailID=mailsheet.getCell(1,1).getContents().toString().trim();
Properties props = new Properties();
String mailprotocol = mailsheet.getCell(2,1).getContents().toString().trim();
String mailprotocoltype = mailsheet.getCell(3,1).getContents().toString().trim();
String mailhost = mailsheet.getCell(4,1).getContents().toString().trim();
String mailhostip = mailsheet.getCell(5,1).getContents().toString().trim();
String mailport=mailsheet.getCell(6,1).getContents().toString().trim();
String mailportid=mailsheet.getCell(7,1).getContents().toString().trim();
props.put(mailprotocol,mailprotocoltype);
props.put(mailhost,mailhostip);
props.put(mailport,mailportid);
javax.mail.Session mailSession =javax.mail.Session.getInstance(props);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmailID));
msg.setSubject("Test Summary");
msg.setContent("<html><body>Dear Admin,<br> Website page "+ "<b><i>"+url + "</b></i>"+" cannot be loaded due to the following :<br> <br></body></html>"+str,"text/html");
Transport.send(msg);
System.out.println("Mail is successfully sent to Recipient address with Error information.");
}
catch(Exception e)
{
//System.out.println(e);
System.out.println("Mail cannot be send to Recipient address due to connection error");
}
}
public void x() {
SendMail(url,driver.getTitle());
}
The answer is probably in the bit of code you don't show us : the part where you test the URL.
The response code for a wrong domain name is different from the response code due to a page not found. Also, depending on the system you're targetting, it's possible that page not found are redirected to the index page, making detection even more difficult.

SMTP connection test

I've been working on a prj(using JAVA SMTPAPI) in which I have to write a program for connectivity with SMTP. I have written a program using help of Google. now plz what I have to do? I have no IDEA further.
any advice or help would be appritiated
I have got this code
package mypackage;
import javax.mail.*;
import java.util.*;
import javax.mail.internet.*;
public class Sendmail {
private String strstmp;
public String getStrstmp() {
return strstmp;
}
public void setStrstmp(String strstmp) {
this.strstmp = strstmp;
}
public void sendMail( String recipients[ ], String subject, String message , String from)
{
// TODO Auto-generated method stub
boolean debug = false;
//set the host smtp addrs
Properties props = new Properties();
props.put("mail.smtp.host",getStrstmp());
//get default session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
//create a new message
Message msg = new MimeMessage(session);
//set the from and to addrs
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressto = new InternetAdrress[recipients.length];
for(i = 0;i<recipients.length;i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
//send message
Transport.send(msg);
}
}
now wat would be addrs of host?
how to do connectivity test ?
Thanks in advance
You need to have access to a SMTP Server. You can install one locally for tests, see search results!

Send automatic mail on specific date through java

I am using Java mail API to send email through my java application. But I want to send it automatically on future date i.e. any specific date of every month/year. I have used my ISP's SMTP server to send email on mentioned id.I have referred the below available example on net. How to set any specific date here.I have tried SimpleDateFormat and set it here but it still sends mail immediately but set its sent date as mentioned specific date. Is there any other way to send automatic email on mentioned date and time?
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// Send a simple, single part, text/plain e-mail
public class TestEmail {
public static void main(String[] args) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "abc#abc.com";
String from = "abc#abc.com";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.yourisp.net";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", 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("Test E-Mail through Java");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
mex.printStackTrace();
}
}
}//End of class
Configure Quartz Job for it. Use cron trigger to specify the execution event
If you're using an EJB 3.0+ container, you could easily use the timer service.
You need to make a session bean, and either implement the TimedObject interface or annotate a method with #Timeout. You can get an instance of the TimerService from the InitialContext via getTimerService(), then create a timer with one of the createTimer() variants. It can take an interval, or a Date object specifying when it expires...

Could not connect to SMTP host: localhost, port: 25 - while REPLYing to mail

I have a code which connects to a mailserver and searches for a particular subject tag and sends response back (REPLY) to that particular mail.
However while giving a reply message I get the following error :
Could not connect to SMTP host: localhost, port: 25
I am able to send email directly the problem occurs only if i use REPLY/FORWARD method.I am using javamail.
import java.util.*;
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.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class Mail {
public static void main(String args[]) throws Exception {
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect("smtp.gotouchpoint.com", "username", "password");
Folder folder = store.getFolder("inbox");
//Connect to the current host using the specified username and password.
try {
//Create a Folder object corresponding to the given name.
// Folder folder = store.getFolder("INBOX");
// Open the Folder.
folder.open(Folder.READ_WRITE);
SearchTerm st1 =new SubjectTerm("**NEW-TICKET**");
Message[] message = folder.search(st1);
//Message[] message = folder.getMessages();
// Create a reply message
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
if(message[i].getSubject().equals("**NEW-TICKET**")) {
System.out.println("new-ticket");
Message forward = new MimeMessage(session);
// Fill in header
forward.setSubject("Fwd: " + message[i].getSubject());
forward.setFrom(new InternetAddress(message[i].getFrom()[0].toString()));
forward.addRecipient(Message.RecipientType.TO,
new InternetAddress("techsupport#touchpointindia.com"));
// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Oiginal message:\n\n");
// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Create and fill part for the forwarded content
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message[i].getDataHandler());
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
forward.setContent(multipart);
System.out.println("msg forward ...." +forward.getSubject());
// Send message
Transport.send(forward);
}
}
System.out.println();
folder.close(true);
store.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
Not sure what might be causing your error.
I'm just taking a wild guess here: Don't use the static Transport.send() method.
Get a transport object and invoke it's sendMessage) method:
[...]
Transport transport = session.getTransport("smtp");
transport.connect(D_HOST, D_PORT, D_USER, D_PASS);
transport.sendMessage(forward, forward.getAllRecipients());
Try and see if this helps.
cheers.

Problem adding buddy with smack api and openfire server

Hi I am new in Java. And its giving me a lot of stress. I need to chat with smack api and openfire server. For this my java code is below
import java.util.*;
import java.io.*;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class RunJabberSmackAPI implements MessageListener{
XMPPConnection connection;
public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1 ",5222,"localhost");
connection = new XMPPConnection(config);
connection.connect();
connection.login(userName, password);
}
public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}
public void displayBuddyList()
{
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
System.out.println("\n\n" + entries.size() + " buddy(ies):");
for(RosterEntry r:entries) {
System.out.println(r.getUser());
}
}
public void disconnect() {
connection.disconnect();
}
public void processMessage(Chat chat, Message message) {
if(message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
public static void main(String args[]) throws XMPPException, IOException {
// declare variables
RunJabberSmackAPI c = new RunJabberSmackAPI();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg;
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
// Enter your login information here
c.login("admin", "admin"); // I created this user with openfire.
c.displayBuddyList();
System.out.println("-----");
System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();
System.out.println("-----");
System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");
while( !(msg=br.readLine()).equals("bye")) {
c.sendMessage(msg, talkTo);
}
c.disconnect();
System.exit(0);
}
}
I run this code twice in my pc. Each for an individual user. I added these two users as friends in openfire by adding rooster.
But when they logged in by running the java code above they send there presence as available . But they can't send their presence to each other available. Instead they receives two error messages from their buddy .
First error message : www.freeimagehosting.net/image.php?eac15f606a.jpg
Second error message : www.freeimagehosting.net/image.php?b827058d07.jpg
I don't know what is wrong with my code. And i really need to solve this problem very soon. I posted this problem other forums too but can't find any answer. So if anyone can have any solution it would be a very big help. Thank You.
In many threads in IgniteRealtime's web you can see that you need to let Smack asynchronously retrieve Roster, so either you change the displayBuddyList() to use a RosterListener instead, or you simply use a Thread.sleep(5000) between the login and the displayBuddyList() function (if you don't want to use a listener, which is recommended) to let it have some time to populate the roster with updated presences.

Categories