How to Send Email via Java Mail 1.4.3 & CKEditor with NetBeans IDE
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:
- Choose File -> New Project -> Java Application. Click Next.
- 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.
- 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)
Most SMTP servers need to authenticate remote users trying to send e-mails. For this reason, we need to create a simple SMTPAuthenticator class in the EmailSender package. This class extends javax.mail.Authenticator and provides a method as follows:
protected PasswordAuthentication getPasswordAuthentication()
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.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





Comments
Sajan Raj replied on Mon, 2010/05/17 - 9:08pm
Hello.. That was a really nice and robust tutorial. I tried out the same with NetBeans and JDK1.6. But I have a problem when I change the layout of the first panel(which has the SMTP parameters) to null layout. The components disappear from the panel and then I have to force it to absolute layout before I can see them again. I checked your code. Seems to be exactly the same. Did you come across any similar problem?
Thanks in advance ;-)
Robert Piesnikowski replied on Tue, 2010/07/06 - 1:37am
in response to: blueproton
Nikunj Aggarwal replied on Mon, 2011/01/24 - 12:13am
Hello,
Pleasec Can you attach the files again.
I downloaded the zip but it was empty.
Robert Piesnikowski replied on Wed, 2011/02/02 - 7:02am
in response to: nikunj2512
Dizzle King replied on Tue, 2011/04/26 - 5:39am
hi piesnikowsk
am developing a standalone email client buttons, am struggling with codimg handling codes for button reply, forward, send, new could you pls help with those codes in java pls
Linh Le replied on Sat, 2011/10/01 - 8:53am
Linh Le replied on Sat, 2011/10/01 - 10:35am
Shilpa Mishra replied on Tue, 2011/10/11 - 2:56pm
Prashant Yadav replied on Thu, 2012/02/02 - 11:34am
Robert
As you know that http://www.megaupload.com has been seized by U.S. District court so all the contentd uploaded there is now unavail.
Will you please mail me this complete code.
My email id is pygold@gmail.com
Thanks.
Nikita Ahluwalia replied on Tue, 2012/02/21 - 1:00pm
in response to: maC_
Matthew Shim replied on Fri, 2012/03/09 - 3:08pm
Robert Piesnikowski replied on Sat, 2012/03/10 - 8:28am
Robert Piesnikowski replied on Sat, 2012/03/10 - 8:30am
Carla Brian replied on Fri, 2012/03/30 - 5:49pm
Robert Piesnikowski replied on Sat, 2012/03/31 - 7:40am
After lot's of email about sending source code I decided to upload again project to downlad for everyone. Source code is available in my blog post http://rpiesnikowski.blogspot.com/2011/06/how-to-send-email-via-java-mail.html at the end of article.
Matt Coleman replied on Tue, 2012/05/08 - 4:25am
graphic artist buffalo has used this and it is awesome
Mateo Gomez replied on Wed, 2012/05/09 - 2:18am
in response to: maC_