DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Postgres JSON Functions With Hibernate 6
  • That’s How You Can Use MapStruct With Lombok in Your Spring Boot Application
  • Implementing PEG in Java

Trending

  • The Convergence of Testing and Observability
  • Spring WebFlux Retries
  • Demystifying Project Loom: A Guide to Lightweight Threads in Java
  • Next.js vs. Gatsby: A Comprehensive Comparison
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How to Send Email via Java Mail 1.4.3 & CKEditor with NetBeans IDE

How to Send Email via Java Mail 1.4.3 & CKEditor with NetBeans IDE

Robert Piesnikowski user avatar by
Robert Piesnikowski
·
Apr. 18, 10 · News
Like (0)
Save
Tweet
Share
78.26K Views

Join the DZone community and get the full member experience.

Join For Free

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:
Libraries

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.

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.

Drop upper

Panel with Controls

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".

Down conent for buttons

Add the two buttons:

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.

 

Java (programming language) Integrated development environment Mail (Apple) NetBeans CKEditor Library

Opinions expressed by DZone contributors are their own.

Related

  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Postgres JSON Functions With Hibernate 6
  • That’s How You Can Use MapStruct With Lombok in Your Spring Boot Application
  • Implementing PEG in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: