Latest Entries »

Monday, June 20, 2011

How to Send Email via Java Mail, CKEditor with NetBeans IDE

This post is copy of my article from here.


Introduction

In this tutorial I will show you how to create a simple JFrame to send email containing HTML content:

This article is divided into several parts, covering topics from the writing of simple e-mail sender Java classes to the integration of a JFrame with CKEditor, which is a rich web HTML editor.


Downloading and Registering Libraries in NetBeans IDE 6.8

First of all, you need to download the latest version of Java Mail from this page, as well as DJ Native Swing. After you download the libraries, you need to put them into the NetBeans Library Manager. I recommend you store all libraries in, for example, C:\Program Files\Java\libraries.


Creating a Java Application and Adding Libraries to the Project

Take the following steps to begin creating the application:
  1. Choose File -> New Project -> Java Application. Click Next.
  2. When Name and Location Window shows up, name your project FCKEditorEmailSender and uncheck Create Main Class so that you end up creating an empty project. Click Finish.
  3. In the Projects Tab click right click Libraries and Add Library from the menu. Then select the libraries which you added from Library Manager. You should have now Java Mail and DJNativeSwing JAR files. Your project should now look like the image shown below:


Creating the Package and Java Classes

Now let's do the real coding work. Go to the project you created and then create a package named EmailSender. In this package, create a Java class named EmailSender (the same name, don't worry) from the New File dialog. In the class, create private fields as shown below:
public class EmailSender {
  private String smtpServer;
  private String port;
  private String user;
  private String password;
  private String auth;
  private String from;
Provide a simple constructor by pressing ALT + INSERT and selecting Constructor... . Select all the fields in the window.

To enable the sending of e-mails by the Java Mail API, you need to create a Properties object where you put all the needed information about SMTP session, such as the server, port, and user. For this purpose create the following method: 
private Properties prepareProperties()
Next, when you prepare the Properties object, you can simply model an email message. This method returns a MimeMessage (which stands for Multipurpose Internet Mail Extensions Message Class). Then create this method:
private MimeMessage prepareMessage(Session mailSession,String charset,
String from, String subject,
String HtmlMessage,String[] recipient) 
The next step about sending emails via Internet involves creating a method for sending HTML content messages. Create this method:
public void sendEmail(String subject,String HtmlMessage,String[] to) 
Now we add the implementations of the methods shown above:
private Properties prepareProperties()
{
   Properties props = new Properties();
   props.setProperty("mail.smtp.host", smtpServer);
   props.setProperty("mail.smtp.port", port);
   props.setProperty("mail.smtp.user", user);
   props.setProperty("mail.smtp.password", password);
   props.setProperty("mail.smtp.auth", auth);
   return props;
}
private MimeMessage prepareMessage(Session mailSession,String charset,
                                        String from, String subject,
                                        String HtmlMessage,String[] recipient) {
        //Multipurpose Internet Mail Extensions
        MimeMessage message = null;
        try {
            message = new MimeMessage(mailSession);
            message.setFrom(new InternetAddress(from));
            message.setSubject(subject);
            for (int i=0;i<recipient.length;i++)
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient[i]));
            message.setContent(HtmlMessage, "text/html; charset=\""+charset+"\"");
        } catch (Exception ex) {
            Logger.getLogger(EmailSender.class.getName()).log(Level.SEVERE, null, ex);
        }
        return message;
    }
public void sendEmail(String subject,String HtmlMessage,String[] to)
    {
        Transport transport = null;
        try {
            Properties props = prepareProperties();
            Session mailSession = Session.getDefaultInstance(
                            props, new SMTPAuthenticator(from, password, true));
            transport =  mailSession.getTransport("smtp");
            MimeMessage message = prepareMessage(mailSession, "ISO-8859-2",
                                                from, subject, HtmlMessage, to);
            transport.connect();
            Transport.send(message);
        } catch (Exception ex) {    
        }
        finally{
            try {
                transport.close();
            } catch (MessagingException ex) {
                Logger.getLogger(EmailSender.class.getName()).
                                                    log(Level.SEVERE, null, ex);
            }
        }
    }
package EmailSender;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SMTPAuthenticator extends Authenticator{
    private String username;
    private String password;
    private boolean needAuth;

    public SMTPAuthenticator(String username, String password,boolean needAuth)
    {
        this.username = username;
        this.password = password;
        this.needAuth = needAuth;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (needAuth)
            return new PasswordAuthentication(username, password);
                else return null;
    }
}


Creating a Swing Form to Provide a Nice GUI

Now that we have finished the e-mail work, we concentrate on the Swing and FCKEditor integration. You need to click right button over package EmailSender and choose New -> JFrame Form, call this class SendEmail and put this class in EmailSender package. Now right click over JFrame Design View and select: Set Layout -> Border Layout.
Now when you try to drop JPanel from Pallete into Design View you will see a few borders which are simpy Content Holders of Border Layout. Please read about BorderLayout from official Java Docs. Click Panel from Pallete and drop panel as is in image below. In this area you will next put controls to get smtp values.
Now right click over the panel above and select : Set Layout -> Null Layout. This will make your controls not floating when user will resize window and secondly controls will be in the same position as it was created in Design view. Test with some diffrent Layouts when you run your application to see what will happen :) Now you will need to create buttons to interact with user. Put new JPanel into lower "Place holder".
Add the two buttons:
And we are close to finishing the tutorial. Last thing to do is put FCKEditor in main method. Modify your:
public static void main(String[] args) 
    UIUtils.setPreferredLookAndFeel();
    NativeInterface.open();
    final String configurationScript =
      "FCKConfig.ToolbarSets[\"Default\"] = [\n" +
      "['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],\n" +
      "['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],\n" +
      "['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],\n" +
      "['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],\n" +
      "'/',\n" +
      "['Style','FontFormat','FontName','FontSize'],\n" +
      "['TextColor','BGColor'],\n" +
      "'/',\n" +
      "['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],\n" +
      "['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote'],\n" +
      "['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],\n" +
      "['Link','Unlink','Anchor'],\n" +
      "['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak', '-', 'ShowBlocks'],\n" +
      "];\n" +
      "FCKConfig.ToolbarCanCollapse = false;\n";
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                htmlEditor = new JHTMLEditor(HTMLEditorImplementation.FCKEditor,
JHTMLEditor.FCKEditorOptions.setCustomJavascriptConfiguration(configurationScript));
                SendEmail es2 = new SendEmail();
                es2.setSize(new Dimension(800,600));
                es2.add(htmlEditor,BorderLayout.CENTER);
                es2.setLocationByPlatform(true);
                es2.setVisible(true);
            }
        });
    }
Now when you replace main method go to your Design View and double click both buttons to generate actionPerformed . Put this codes into proper buttons.Notice that I used code below to provide new Thread to prevent block Graphical User Interface during send e-mail:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
  public void run() {
    emailer.sendEmail(subject.getText(),
    htmlEditor.getHTMLContent(),
    recipientsString); 
    }
});  
private void sendEmailActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
                StringTokenizer recepientsTokenizer = new StringTokenizer(to.getText(), ",");
                final String[] recipientsString = new String[recepientsTokenizer.countTokens()];
                for (int i = 0; i < recipientsString.length; i++) {
                    recipientsString[i] = recepientsTokenizer.nextToken();
                }
                 final EmailSender emailer = new EmailSender(smtpServer.getText(),
                        port.getText(), username.getText(),
                        password.getPassword().toString(),
                        "true", from.getText());
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                emailer.sendEmail(subject.getText(),
                        htmlEditor.getHTMLContent(),
                        recipientsString);
            }
        });
    }
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  // TODO add your handling code here:
  dispose();
} 
Now you can build your project and show off to your friends :)
Here you can download the packed NetBeans project.
Tip:
When you download DJ Native you can double-click the DJNativeSwing-SWTDemo.jar to look closer into the various amazing classesm such as JWebBrowser JHtmlEditor with different HtmlEditors.

After many reqests for source code of project which was unavailable due to closed magaupload I uploaded project one time more. So I Uploaded again source code. 

3 comments:

MOUPOJOU Emmanuel said...

Good Morning, and thank you very much for this example.
I downloaded the project , but when running the space reserved for htmlEditor is completly white.
Help me please.

mahesh said...

Thank you very much...

Unknown said...
This comment has been removed by the author.

Post a Comment