viernes, 19 de noviembre de 2010

Lanzar aplicaciones con retraso al iniciar windows 7

Como todos sabéis Windows tiene varios mecanismos para lanzar aplicaciones en el arranque del sistema operativo. La fórmula más conocida es colocar un acceso directo en la carpeta "Inicio". Pero hoy me encuentro con el problema de lanzar una aplicación que hace uso de la tarjeta gráfica y el problema consiste es que al poner la aplicación en la carpeta de Inicio esta se lanza antes de que se cargue el servicio de DirectX por lo que la aplicación da un fallo de no estar aún enable dichas funcionalidades. La manera de resolver el problema ha sido construir un pequeño script en bacth (lenguaje de script de MS-DOS) para que espero lo necesario hasta que los servicios gráficos hayan sido cargados.

Os dejo el script:

---------------------
@echo off
timeout 30
start chrome
------------------
"@echo off" -> no imprima la salida de los comandos por la consola
"timeout 30" -> espere 30 segundos (tiempo suficiente para el arranque de todos los servicios de windows 7
"start chrome" -> arrancar la aplicación

Lo guardais como loquequerais.bat y lo colocais en la carpeta de "Inicio"


Sintasis del comando start
Syntax
      START "title" [/Dpath] [options] "command" [parameters]

Key:
   title      : Text for the CMD window title bar (required)
   path       : Starting directory
   command    : The command, batch file or executable program to run
   parameters : The parameters passed to the command

Options:
   /MIN       : Minimized
   /MAX       : Maximized
   /WAIT      : Start application and wait for it to terminate
   /LOW       : Use IDLE priority class
   /NORMAL    : Use NORMAL priority class
   /HIGH      : Use HIGH priority class
   /REALTIME  : Use REALTIME priority class

   /B         : Start application without creating a new window. In this case
                ^C will be ignored - leaving ^Break as the only way to
                interrupt the application
   /I         : Ignore any changes to the current environment.

   Options for 16-bit WINDOWS programs only

   /SEPARATE   Start in separate memory space (more robust)
   /SHARED     Start in shared memory space (default)

miércoles, 27 de octubre de 2010

Mi primera DLL

Hoy he decidido grabarme un video construyendo una dll básica en c++ y consumiendola desde una aplicación de consola en c++ porque es una tarea util cuando necesitas hacer un wrapper de una librería en c o c++ y usarla desde otros lenguajes como c#. Aunque es algo muy fácil me cuesta muchas veces recordar la nomenglatura de ahí la idea de este tutorial espero que os sea útil para arrancar vuestros proyectos.




El codigo fuente de la dll sería:


#include "stdafx.h"

#define DLL_EXPORT extern "C" __declspec(dllexport)

DLL_EXPORT double Sum(double a, double b);

double Sum(double a, double b)
{
return a+b;
}



y el de la clase en c++ que lo consume sería:


#include "stdafx.h"

#include <iostream>

extern "C" __declspec(dllimport)double Sum(double a, double b);

using namespace std;

int main(){
cout << "hola dll" << endl;
cout << "La suma de 2 + 3 es:" << Sum(2,3);

getchar();
return 0;
}


Y ahora en este segundo video creo un proyecto de consola de c# desde
el cual también consumiremos los métodos de nuestra DLL.



El código de la clase Wrapper:


namespace UseDLLCSharp
{
    class WrapperDLL
    {
        [DllImport("DLL.dll")]
        public static extern double Sum(double a, double b);
    }
}



El código de la clase principal de C#:


namespace UseDLLCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hola mundo");
            Console.WriteLine("La suma de 3 + 2 es: " + WrapperDLL.Sum(3, 2));

            Thread.Sleep(5000);
        }
    }
}

martes, 19 de octubre de 2010

La evolución de un programador

Hoy encontré un artículo super divertido sobre la evolución que sufre una programador al ir ascendiendo de cargo o rango con los años, no es perdáis el final.


High School/Jr.High

  10 PRINT "HELLO WORLD"
  20 END

First year in College

  program Hello(input, output)
    begin
      writeln('Hello World')
    end.

Senior year in College

  (defun hello
    (print
      (cons 'Hello (list 'World))))

New professional

  #include <stdio.h>
  void main(void)
  {
    char *message[] = {"Hello ", "World"};
    int i;

    for(i = 0; i < 2; ++i)
      printf("%s", message[i]);
    printf("\n");
  }

Seasoned professional

  #include <iostream.h>
  #include <string.h>

  class string
  {
  private:
    int size;
    char *ptr;

  string() : size(0), ptr(new char[1]) { ptr[0] = 0; }

    string(const string &s) : size(s.size)
    {
      ptr = new char[size + 1];
      strcpy(ptr, s.ptr);
    }

    ~string()
    {
      delete [] ptr;
    }

    friend ostream &operator <<(ostream &, const string &);
    string &operator=(const char *);
  };

  ostream &operator<<(ostream &stream, const string &s)
  {
    return(stream << s.ptr);
  }

  string &string::operator=(const char *chrs)
  {
    if (this != &chrs)
    {
      delete [] ptr;
     size = strlen(chrs);
      ptr = new char[size + 1];
      strcpy(ptr, chrs);
    }
    return(*this);
  }

  int main()
  {
    string str;

    str = "Hello World";
    cout << str << endl;

    return(0);
  }

Master Programmer

  [
  uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820)
  ]
  library LHello
  {
      // bring in the master library
      importlib("actimp.tlb");
      importlib("actexp.tlb");

      // bring in my interfaces
      #include "pshlo.idl"

      [
      uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820)
      ]
      cotype THello
   {
   interface IHello;
   interface IPersistFile;
   };
  };

  [
  exe,
  uuid(2573F890-CFEE-101A-9A9F-00AA00342820)
  ]
  module CHelloLib
  {

      // some code related header files
      importheader(<windows.h>);
      importheader(<ole2.h>);
      importheader(<except.hxx>);
      importheader("pshlo.h");
      importheader("shlo.hxx");
      importheader("mycls.hxx");

      // needed typelibs
      importlib("actimp.tlb");
      importlib("actexp.tlb");
      importlib("thlo.tlb");

      [
      uuid(2573F891-CFEE-101A-9A9F-00AA00342820),
      aggregatable
      ]
      coclass CHello
   {
   cotype THello;
   };
  };


  #include "ipfix.hxx"

  extern HANDLE hEvent;

  class CHello : public CHelloBase
  {
  public:
      IPFIX(CLSID_CHello);

      CHello(IUnknown *pUnk);
      ~CHello();

      HRESULT  __stdcall PrintSz(LPWSTR pwszString);

  private:
      static int cObjRef;
  };


  #include <windows.h>
  #include <ole2.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include "thlo.h"
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "mycls.hxx"

  int CHello::cObjRef = 0;

  CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk)
  {
      cObjRef++;
      return;
  }

  HRESULT  __stdcall  CHello::PrintSz(LPWSTR pwszString)
  {
      printf("%ws
", pwszString);
      return(ResultFromScode(S_OK));
  }


  CHello::~CHello(void)
  {

  // when the object count goes to zero, stop the server
  cObjRef--;
  if( cObjRef == 0 )
      PulseEvent(hEvent);

  return;
  }

  #include <windows.h>
  #include <ole2.h>
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "mycls.hxx"

  HANDLE hEvent;

   int _cdecl main(
  int argc,
  char * argv[]
  ) {
  ULONG ulRef;
  DWORD dwRegistration;
  CHelloCF *pCF = new CHelloCF();

  hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

  // Initialize the OLE libraries
  CoInitializeEx(NULL, COINIT_MULTITHREADED);

  CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER,
      REGCLS_MULTIPLEUSE, &dwRegistration);

  // wait on an event to stop
  WaitForSingleObject(hEvent, INFINITE);

  // revoke and release the class object
  CoRevokeClassObject(dwRegistration);
  ulRef = pCF->Release();

  // Tell OLE we are going away.
  CoUninitialize();

  return(0); }

  extern CLSID CLSID_CHello;
  extern UUID LIBID_CHelloLib;

  CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */
      0x2573F891,
      0xCFEE,
      0x101A,
      { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
  };

  UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */
      0x2573F890,
      0xCFEE,
      0x101A,
      { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
  };

  #include <windows.h>
  #include <ole2.h>
  #include <stdlib.h>
  #include <string.h>
  #include <stdio.h>
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "clsid.h"

  int _cdecl main(
  int argc,
  char * argv[]
  ) {
  HRESULT  hRslt;
  IHello        *pHello;
  ULONG  ulCnt;
  IMoniker * pmk;
  WCHAR  wcsT[_MAX_PATH];
  WCHAR  wcsPath[2 * _MAX_PATH];

  // get object path
  wcsPath[0] = '\0';
  wcsT[0] = '\0';
  if( argc > 1) {
      mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1);
      wcsupr(wcsPath);
      }
  else {
      fprintf(stderr, "Object path must be specified\n");
      return(1);
      }

  // get print string
  if(argc > 2)
      mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1);
  else
      wcscpy(wcsT, L"Hello World");

  printf("Linking to object %ws\n", wcsPath);
  printf("Text String %ws\n", wcsT);

  // Initialize the OLE libraries
  hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED);

  if(SUCCEEDED(hRslt)) {


      hRslt = CreateFileMoniker(wcsPath, &pmk);
      if(SUCCEEDED(hRslt))
   hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello);

      if(SUCCEEDED(hRslt)) {

   // print a string out
   pHello->PrintSz(wcsT);

   Sleep(2000);
   ulCnt = pHello->Release();
   }
      else
   printf("Failure to connect, status: %lx", hRslt);

      // Tell OLE we are going away.
      CoUninitialize();
      }

  return(0);
  }

Apprentice Hacker

  #!/usr/local/bin/perl
  $msg="Hello, world.\n";
  if ($#ARGV >= 0) {
    while(defined($arg=shift(@ARGV))) {
      $outfilename = $arg;
      open(FILE, ">" . $outfilename) || die "Can't write $arg: $!\n";
      print (FILE $msg);
      close(FILE) || die "Can't close $arg: $!\n";
    }
  } else {
    print ($msg);
  }
  1;

Experienced Hacker

  #include <stdio.h>
  #define S "Hello, World\n"
  main(){exit(printf(S) == strlen(S) ? 0 : 1);}

Seasoned Hacker

  % cc -o a.out ~/src/misc/hw/hw.c
  % a.out

Guru Hacker

  % echo "Hello, world."

New Manager

  10 PRINT "HELLO WORLD"
  20 END

Middle Manager

  mail -s "Hello, world." bob@b12
  Bob, could you please write me a program that prints "Hello, world."?
  I need it by tomorrow.
  ^D

Senior Manager

  % zmail jim
  I need a "Hello, world." program by this afternoon.

Chief Executive

  % letter
  letter: Command not found.
  % mail
  To: ^X ^F ^C
  % help mail
  help: Command not found.
  % damn!
  !: Event unrecognized
  % logout



(Lo encontre en fuente)

martes, 3 de agosto de 2010

Renombrar ficheros desde Java

Hoy tuve que hacer un programita muy tonto pero que me quitó muchas horas
de trabajo de monos, así que os dejo el código por si a alguien le sirve
del mismo modo que a mí.

El programa lo que hace es renombrar todos los ficheros de un directorio
desde java. Este directorio estaba lleno de imagenes en formato png y lo
que tuve que hacer es añadir al final del nombre la coletilla "_thumb" que
viene de thumbnail.

Código


package renombradodeficheros;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
*
* @author Jorge
*/
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        
        String path = "resources/directory/";

        File directory = new File(path);
        String[] files = directory.list();
        File f1,f2;
        String filename, filenameModif;
        int cutindex;
        for (int i = 0; i < files.length; i++) {

            filename = files[i];
            f1 = new File(path+"/"+filename);
            cutindex = filename.indexOf(".png");
            if (cutindex != -1)
            {
                filenameModif = filename.substring(0, cutindex)+"_thumb.png";
                f2 = new File(path+"/"+filenameModif);
                if (f1.renameTo(f2))
                    System.out.println("Renombrado");
                else
                    System.out.println("Fallo al renombrar");
            }
        }
    }
}

Trabajar con XML y C#

Hola a todos,

Hace tiempo que no escribo en el blog pero es que últimamente ando muy muy liado con los diferentes proyectos que estamos desarrollando en Syderis. Hoy os pongo un pequeño ejemplo de como leer y escribir XML con la API de .NET framework y C#.

Dado el xml:

<?xml version="1.0" encoding="utf-8" ?>
<sample>
<equipments>
   <equipment type="tipo1">
     <point x="1900" y="1000">
       <title>Titulo</title>
       <image >DSCN2903</image>
       <description>Esta es la descripción del primer punto</description>    
     </point>
     <point x="1000" y="2300">
       <title>Titulo</title>
       <image />DSCN2903
       <description>mirador2</description>    
     </point>
   </equipment>
</equipments>
</sample>



Código del lector:


public void Read(string filename)
       {
           XmlDocument xml = new XmlDocument();
           try
           {
               xml.Load(filename);
               XmlNodeList nodeEquipments = xml.GetElementsByTagName("Equipments");

               //Equipamientos
               XmlNodeList equipmentsNodes = ((XmlElement)nodeEquipments[0]).GetElementsByTagName("equipment");
               string sfilename;
               string stitle;
               string sdescription;
               string sx, sy;
               foreach (XmlElement equipment in equipmentsNodes)
               {
                   string stype = equipment.GetAttribute("type");
                   XmlNodeList pointsNodes = equipment.GetElementsByTagName("point");
                            
                          
                   foreach (XmlElement pointNode in pointsNodes)
                   {
                       sx = pointNode.GetAttribute("x");
                       sy = pointNode.GetAttribute("y");
                       stitle = pointNode.GetElementsByTagName("title")[0].InnerText;
                       sfilename = pointNode.GetElementsByTagName("image")[0].InnerText;
                       sdescription = pointNode.GetElementsByTagName("description")[0].InnerText;                      
                       Console.Writeline("type:"+stype+" coord:"+sx+sy+" filename"+sfilename+" title:"stitle+" description:"+sdescription);

                   }
              
               }
          
           }
           catch (XmlException e)
           {
               Console.WriteLine("XML file load Failure." + e.ToString());
           }
}




Código escritor:


public void Write(string filename)
       {
           XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
           xmlWriter.Formatting = Formatting.Indented;
           xmlWriter.WriteStartDocument();

           xmlWriter.WriteStartElement("Sample");

           //Equipments
           xmlWriter.WriteStartElement("Equipments");

           foreach (string etype in equipments.keys)
           {
               xmlWriter.WriteStartElement("equipment");
               xmlWriter.WriteAttributeString("type", etype);

               foreach (Equipment e in equipments[etype])
               {
                   //<point x="100" y="100">
                   xmlWriter.WriteStartElement("point");
                   xmlWriter.WriteAttributeString("x", e.Point.X.ToString());
                   xmlWriter.WriteAttributeString("y", e.Point.Y.ToString());

                   xmlWriter.WriteStartElement("title");
                   xmlWriter.WriteString(e.Title);
                   xmlWriter.WriteEndElement();

                   //<image />filename
                   xmlWriter.WriteStartElement("image");
                   xmlWriter.WriteString(e.Image);
                   xmlWriter.WriteEndElement();

                   //<description>mirador</description>
                   xmlWriter.WriteStartElement("description");
                   xmlWriter.WriteString(e.Description);
                   xmlWriter.WriteEndElement();

                   xmlWriter.WriteEndElement(); // End point
               }
               xmlWriter.WriteEndElement(); //End equipment
           }

           xmlWriter.WriteEndElement(); //End Equipments

           xmlWriter.WriteEndElement(); //End Sample

           xmlWriter.Flush();
           xmlWriter.Close();

       }

martes, 2 de febrero de 2010

Conectarse con el puerto Serie/paralelo desde Java

Bien pues para esta tarea existe una librería llamada Java Comunication API. Pero hay que tener en cuenta que para comunicarte a través de algo físico de la máquina Java nos proporciona una fachada de métodos que por debajo se conectan con diferentes drivers según si estamos corriendo el programa en un windows, macos o linux. Esto quiere decir que además de tener la máquina virtual de java instalada tendrás que instalar un driver en el sistema operativo. Yo empece a trabajar con la implementación de Sun pero me dió muchos problemas y no conseguía que me detectara los drivers instalados, así que finalmente opte por usar una implementación de Java Comunication API open source llamada RXTX. Con ella fue todo rodado por lo que os recomiendo que la useís.

Su página web es http://rxtx.qbang.org/

La instalación es muy simple os bajais la librería en la que os viene:

- RXTXcomm.jar (librería que implementa la especificación de Java Comunication API)
- Directorio con drivers para Linux
- Directorio con drivers para Solaris
- Directorio con drivers para Mac_OS_X
- Directorio con drivers para Windows


Añadis RXTXcomm.jar como librería a vuestro proyecto java y el driver lo meteis en la instalación del jre\bin

Ahora la implementación de una conexión al puerto serie.


public class EjemploRXTX {
    static CommPortIdentifier portId;
    static CommPortIdentifier saveportId;
    static Enumeration  portList;
    static InputStream inputStream;
    static OutputStream outputStream;
    static BufferedInputStream bufferedInputStream;
    static SerialPort  serialPort;
   
   
    public static void main(String[] args){
        boolean gotPort = false;
        String port;
        portList = CommPortIdentifier.getPortIdentifiers();
       
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement(); //get next port to check
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if ( portId.getName().equals("COM4") ) {
                    port = portId.getName();
                    gotPort = true;
                }
               
                if (gotPort == true) {
                    try {
                        serialPort = (SerialPort)portId.open("SMSSender", 2000);
                    } catch (PortInUseException ex) {
                        ex.printStackTrace();
                    }
                    try {
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    try {
                        serialPort.setSerialPortParams(19200,
                                SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_2,
                                SerialPort.PARITY_NONE
                                );
                    } catch (UnsupportedCommOperationException ex) {
                        ex.printStackTrace();
                    }
                   
                    try {
                        inputStream = serialPort.getInputStream();
                        bufferedInputStream = new BufferedInputStream(inputStream);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                   
                    serialPort.notifyOnDataAvailable(true);
                }
            }
        }
       
       //Escribir en el puerto serie
       try {
            if (!(outputStream == null))
                outputStream.write("array de váis que queremos enviar");
           
            byte[] readBuffer = new byte[1];
            boolean read = false;
            while(!read) {
                try {
                    String getInfo = "";
                    Thread.sleep(100);
                    while (bufferedInputStream.available() > 0) {
                        int numBytes = bufferedInputStream.read(readBuffer);
                        getInfo += new String(readBuffer);
                        read = true;
                    }
                    feedback += getInfo;
                    int length = getInfo.length();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }



En este ejemplo se usa por debajo una plataforma windows como podéis ver en el nombre del puerto "COM4" en un linux por ejemplo este sería algo como "/dev/ttyS0".

Tambíen para cada caso teneis que tener en cuenta que los datos de conexión con el dispositivo son particulares a cada dispositivo:


serialPort.setSerialPortParams(19200,
                                SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_2,
                                SerialPort.PARITY_NONE
                                );


El dispositivo de este ejemplo trabajaba a 19200 baudios, tamaño de mensaje 8 bits, sin paridad y con el bit de parada 2.

Si ajustais estas cosas ya os debe funcionar para cualquier dispositivo.

Enviar email desde Java 2º parte

Para usar el SMTP de google y nuestra cuenta de gmail tendremos que modificar el ejemplo anterior ya que google usa encriptación por SSL para la autenticación. A continuación el como se haría:


public class Main {
    
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Esto sería el mensaje";
    private static final String emailSubjectTxt = "Aqui el asunto";
    private static final String emailFromAddress = "micuenta@gmail.com";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "Email destino"};
    
    
    public static void main(String args[]) throws Exception {
        
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        
        new Main().sendSSLMessage(sendTo, emailSubjectTxt,emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
    }
    
    public void sendSSLMessage(String recipients[], String subject,String message, String from) throws MessagingException {
        boolean debug = true;
        
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        
        Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
            
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("micuenta@gmail.com", "micontraseñadegmail");
            }
        });
        
        session.setDebug(debug);
        
        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        
        
        msg.setSubject(subject);
        
        msg.setText(message);
        Transport.send(msg);
    }
}

Como enviar emails desde Java

Hace ya un tiempo que no escribo en el blog, pero es que últimamente he estado muy muy liado, lo bueno es que he tenido que trabajar en muchos proyectos lo cuál me permitirá escribir unos cuantos tutoriales este més.

Para este primer tutorial he decidido poner un ejemplo de algo que puede parecer una tontería "enviar un correo electrónico desde Java" pero si no encuentra un buen ejemplo en la red puedes pegarte un buen rato.

Lo primero debemos bajarnos la librería JavaMail.jar y activation.jar y añadirlos a nuestro proyecto.


Nota. No preocuparse son dos jar de poco peso.


En principio creamos una clase para el envío de emails:



public class SendMail {
    
    private String from;
    private String to;
    private String subject;
    private String text;
    private ITracer tracer;
    
    public SendMail(String from, String to, String subject, String text){
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.text = text;
        tracer = FileTracer.getInstance();
    }
    
    public void send(){
        
        Properties props = new Properties();
        props.put("mail.smtp.host", "ServidorSMTP");
        props.put("mail.smtp.port", "25"); //Suele ser este puerto
        props.put("mail.smtp.auth", "true");
                
        Session mailSession = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
            
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("UsuarioSMTP",
                                                  "PasswordSMTP");
            }
        });
        
        Message simpleMessage = new MimeMessage(mailSession);
        
        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;
        try {
            fromAddress = new InternetAddress(from);
            toAddress = new InternetAddress(to);
        } catch (AddressException e) {
            tracer.send(ITracer.INFO,e.getMessage());
        }
        
        try {
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipient(RecipientType.TO, toAddress);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(text);
            
            Transport.send(simpleMessage);
            
            tracer.send(ITracer.INFO,"Email enviado a "+toAddress);
        } catch (MessagingException e) {
            tracer.send(ITracer.INFO,e.getMessage());
        }
    }
    
    public void setSubject(String subject)
    {
        this.subject = subject;
    }
    
    public void setText(String message)
    {
        this.text = message;
    }
}



Y por último sólo nos queda usarlo:



SendMail mail = new SendMail("FromEmail",
                                             "ToEmail",
                                             "Asunto",
                                             "Mensaje");
mail.send();



Un saludo y espero que os sea útil ;)