JAVA – Send email From JAVA Application & Command Line – Febootimail

 

Sending an email from a JAVA application.

I’ve discovered another great tool this week – Febootimail.
It allows you to send an email from the command line – meaning that you can send an email from any JAVA application running on a windows OS. Not just basic emails, but HTML email, attachments etc.

 

STEP 1 Download & Install febootimail.exe:

The Febootimail application can be downloaded from the following location –
http://www.febooti.com/downloads/
and look for the setup / installer EXE.

Once downloaded run the setup process – the default setup location is C:\Program Files\febooti Command line email\

When the install is complete navigate to the install directory and look for a file called febootimail.exe.
This is the EXE that you will call from your JAVA application. If you only intend running your application on your local pc then this is fine. I run it from a server side application, so copied febootimail.exe to a server location accessible from all the clients running my JAVA app.

 

STEP 2 Call Febootimail.exe From the Application:

The following is an extract from a simple class that will send an email.

 

 

try{

          String cmd;

          cmd = “ C:\Program Files\febooti Command line email\febootimail.exe”; // LINE1

          cmd += ” -SERVER mail.yourserver.net”;//LINE 2

          cmd += ” -FROM info@yourdomain.co.uk”; // LINE 3

          cmd += ” -TO toaddress@whoever.com” ; // LINE 4

          cmd += ” -MSG This is the body of the email address”; // LINE 5

          cmd += ” -HTML “; // LINE 6

          cmd += ” -SUBJ This Is The Subject”; // LINE 7

          cmd += ” -FROMNAME fromaddress@yourdomain.com”; // LINE 8

          cmd += ” -AUTH AUTO -USER username -PASS password “; // LINE 9

          Process p = Runtime.getRuntime().exec(cmd);

}

catch(Exception e){

            e.printStackTrace();

}

 

 

Line 1: Points JAVA to febootimain.exe. Change the location depending on where you placed the exe.
Line 2:  Supply your mail server name.
Line 3: Supply a FROM address.
Line 4: the recipient email address.
Line 5: This is the message body. This could be HTML code.
Line 6: Tells febootimail.exe to expect HTML in the message body.
Line 7: Sets the subject.
Line 8: sets the from name – this will abear as the sender alias.
Line 9: The username and password for your mail server.

Advertisements

JAVA – JFreeChart – graphs and charts in JAVA

 

I came across a fantastic tool this week for creating graphs and charts in JAVA – JFreeChart.

The JARs and API can be downloaded from the following link:
http://www.jfree.org/jfreechart/download.html

 

STEP 1:
Once downloaded, the first step is to unzip the content and look for 2 files called –
jcommon-1.0.14.jar and jfreechart-1.0.11.jar
The file names may change slightly with new releases.
Copy these 2 files into the working directory of your JAVA application – adding then to the class path. 

 
 

 

If using Netbeans, copy jcommon-1.0.14.jar andjfreechart-1.0.11.jar to the project folder in windows explorer.
In Netbeans – right-click the project in the projects window and select properties.
Select the Libraries category.
On the Compile tab click Add JAR/Folder.
Select jcommon-1.0.14.jar andjfreechart-1.0.11.jar  and click open.
Click OK.
jcommon-1.0.14.jar andjfreechart-1.0.11.jar are now in the class path of the current JAVA application.

 

STEP 2 Creating a pie chart in a swing application:

I have found that jScrollPane is a use full object to hold the chart. When building your Jframe add an empty JScrollPane somewhere on your window that will hold the chart.

The following example assumes that the JFrame is already created and Pack() has been called.

Add the following 3 methods into the GUI class:

   // CREATE THE PIE CHART
   public static JPanel createPiePanel() {

        JFreeChart pieChart = createPieChart(createPieDataset());

        return new ChartPanel(pieChart);

    }

   
    // BUILD THE PIE CHART

    private static JFreeChart createPieChart(PieDataset dataset) {

 

        JFreeChart chart = ChartFactory.createPieChart(

            “Chart Title”,  // chart title

            dataset,             // data

            true,               // include legend

            true,

            false

        );

 

        PiePlot plot = (PiePlot) chart.getPlot();

        plot.setSectionOutlinesVisible(false);

        plot.setNoDataMessage(“No data available”);

 

        return chart;

 

    }

   

    // CREATE THE PIE CHART DATA

    private static PieDataset createPieDataset() {

        DefaultPieDataset dataset = new DefaultPieDataset();

       

        dataset.setValue(“One”, new Double(43.2));

        dataset.setValue(“Two”, new Double(10.0));

        dataset.setValue(“Three”, new Double(27.5));

        dataset.setValue(“Four”, new Double(17.5));

        dataset.setValue(“Five”, new Double(11.0));

        dataset.setValue(“Six”, new Double(19.4));

 

         return dataset;

    }

 

 

 

 

 

STEP 3: Add the created pie chart into an already existing JScrollPane:

Assuming the there is a valid JScrollPane in the main GUI of the Swing application, use the following code to add the chart to it.

// REMOVE ANY ITEM CURRENTLY IN THE JCROLLPANE
JScrollPane.getViewport().removeAll();


// BUILD AND ADD THE CHART TO THE JSCROLLPANE

JScrollPane.getViewport().add(createPiePanel());

When this is teamed with a JDBC (https://robbamforth.wordpress.com/2008/10/28/java-sql-server-2005-odbc-jdbc-connection/) you can build up graphs based on SQL data.

 

You can learn how wo export the chart to a JPEG feil here: https://robbamforth.wordpress.com/2008/11/05/java-jfreechart-how-to-save-a-jcfreechart-to-jpeg-file/

JAVA SQL SERVER 2005 ODBC / JDBC CONNECTION

 

This artice explains how to create a connection to a SQL Server 2005 database from a JAVA application.

Step 1:
Download the JDBC driver from the folloiwing Microsoft site:
http://www.microsoft.com/downloads/details.aspx?FamilyID=e22bc83b-32ff-4474-a44a-22b6ae2c4e17&displaylang=en

Microsoft installation instructions:

  1. Download sqljdbc_<version>_enu.exe to a temporary directory.
  2. Run sqljdbc_<version>_enu.exe.
  3. Enter an installation directory when prompted. We recommend that you unpack this zip file in %ProgramFiles% with the default directory: “Microsoft SQL Server 2005 JDBC Driver”.

 

Step 2:
Locate the file called sqljdbc4.jar within the installation directory for the JDBC driver. Currently the JAR file can be found in %Microsoft SQL Server 2005 JDBC Driver\sqljdbc_2.0\enu.
Copy this JAR file into the class path of your JAVA application.

If using Netbeans, copy sqljdbc4.jar to the project folder in windows explorer.
In Netbeans – right-click the project in the projects window and select properties.
Select the Libraries catagory.
On the Compile tab click Add JAR/Folder.
Select sqljdbc4.jar and click open.
Click OK.
sqljdbc4.jar is now in the class path of the current JAVA application.

 

Step 3: CREATE A CLASS IN YOUR CURRENT APPLICATION CALLED MyConnection
The myConnection class instantiates the connection the SQL Server using the JDBC.

Enter the code exactlyas it appears below omitting your information for the following:

USERNAME = your SQL account username
PASSWORD = your SQL account password
SERVERNAME = your SQL servername e.g. SQL-SERV-1. The IP address of the SQL server can be used instead.
DATABASENAME = the name of the database connecting to.

 

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

import java.sql.Connection;

import java.sql.DriverManager;

 

class MyConnection {

  public static Connection getConnection() throws Exception {

     

      Connection con = null;

      try{

      SQLServerDataSource ds = new SQLServerDataSource();

      ds.setUser(“USERNAME”);

      ds.setPassword(“PASSWORD”);

      ds.setServerName(“SERVERNAME”);

      // ds.setServerName(“xxx.xxx.x.xx”);

      ds.setPortNumber(1433);

      ds.setDatabaseName(“DATABASENAME”);

      con = ds.getConnection();

     

      }catch(Exception e){

          e.printStackTrace();

      }

     

      return con;

 

    }

} 

 

 

STEP 5: Quering the database using a class called JDBCTest

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

/**

 *

 * @author Rob.Bamforth

 */

public class JDBCTest {

 

    static Connection theConn;

   

    public JDBCTest(){

       

        try {       

                    theConn = MyConnection.getConnection();

                    ResultSet rs;

                    Statement stmt;

 

String sql =  “select top 100 title, forename, surname from DATA.DBO.CUSTOMERS”;

                    stmt = theConn.createStatement();               

                    rs = stmt.executeQuery(sql);

                    while (rs.next()) {                                                

                                               

                        System.out.println(

                            “Title: ” + rs.getString(1).trim() +

                            ” Forename: ” + rs.getString(2).trim() +

                            ” Surname: ” + rs.getString(3).trim()

                        );                                             

                       

                    }   

                } catch (SQLException ex) {

                    ex.printStackTrace();

                } catch (Exception ex) {

                    ex.printStackTrace();

                }

       

    }           

   

    public static void main(String args[]) {

        new JDBCTest();

    }

       

}

 

The above code selects the top 100 title, forename, surname from the database DATA.DBO.CUSTOMERS.

 

rs.getString(1).trim() returns eliment 1 in the select list.  

rs.getString(2).trim() returns eliment 2 in the select list.

rs.getString(3).trim() returns eliment 3 in the select list etc.

 

 

SQL Server Allow users to access sp_send_dbmail to send email

After setting up an email account / profile in SQL server (https://robbamforth.wordpress.com/2008/10/21/sql-server-2005-database-mail/) you must give each user account permission to access the sp_send_dbmail procedure.

This is done in the following way:

When setting up a new user, select the User Mapping option from the left hand side of the screen.
Scroll down to the MSDB database and tick the box next to it.
Under Database role Membership for:MSDB select DatabaseMailUserRole.
Complete the new user set up as usual.

This user now has permission to access procedures using the sp_send_dbmail command, such as sending database mail:

EXEC msdb.dbo.sp_send_dbmail

    @profile_name = EMAIL_PROFILE’,

    @recipients = test@test.som’,

    @subject = ‘This is a test email’,

    @body = ‘Sample Message’,    

    @body_format = ‘HTML’;

 

 

JAVA replace string within a string

The following code replaces an instance of a string within a string:

String testString = “This is a text string”
testString = testString.replace(“text string”, “sentance”);

testString will now print “This is a sentance”.

The replace() function is case sensative, and will only carry out the replace if the case matches both strings.

Select column names and column data from SQL table

In SQL Management Studio Select the database environment that contains the table that you want to query.
The following command displays all the columns in all the table in thje current database:

select * from information_schema.columns

 You will notice that this result set returns usefull data on the table.

To select this information from a specific table in the  database,
use the following command:

select * from information_schema.columns

where TABLE_NAME = ‘YOURTABLE’

  where YOURTABLE is the name of the table you wish to select on.