The code snippet below show you how to create a simple Java Swing application that can be used to send an e-mail. The program allows user to supply the from
email address, to
email address, the subject and the message of the email. User need to select the available SMTP server to connect to and provide the username and password for authentication to the mail server.
Here is the user interface of this simple email client:
The main routine for sending the email is in the SendEmailActionListener
class, which is an implementation of an ActionListener
interface that will handle email sending process when Send E-mail
button is pressed.
package org.kodejava.mail;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;
public class SendEmailClient extends JFrame {
private final JTextField fromField = new JTextField();
private final JTextField toField = new JTextField();
private final JTextField subjectField = new JTextField();
private final JComboBox<String> mailSmtpHostComboBox = new JComboBox<>();
private final JTextField usernameField = new JTextField();
private final JPasswordField passwordField = new JPasswordField();
private final JTextArea contentTextArea = new JTextArea();
private SendEmailClient() {
InitializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SendEmailClient client = new SendEmailClient();
client.setVisible(true);
});
}
private void InitializeUI() {
setTitle("Send E-mail Client");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(new Dimension(500, 500));
getContentPane().setLayout(new BorderLayout());
// Header Panel
JPanel headerPanel = new JPanel();
headerPanel.setLayout(new GridLayout(6, 2));
headerPanel.add(new JLabel("From:"));
headerPanel.add(fromField);
headerPanel.add(new JLabel("To:"));
headerPanel.add(toField);
headerPanel.add(new JLabel("Subject:"));
headerPanel.add(subjectField);
headerPanel.add(new JLabel("SMTP Server:"));
headerPanel.add(mailSmtpHostComboBox);
mailSmtpHostComboBox.addItem("smtp.gmail.com");
headerPanel.add(new JLabel("Username:"));
headerPanel.add(usernameField);
headerPanel.add(new JLabel("Password:"));
headerPanel.add(passwordField);
// Body Panel
JPanel bodyPanel = new JPanel();
bodyPanel.setLayout(new BorderLayout());
bodyPanel.add(new JLabel("Message:"), BorderLayout.NORTH);
bodyPanel.add(contentTextArea, BorderLayout.CENTER);
JPanel footerPanel = new JPanel();
footerPanel.setLayout(new BorderLayout());
JButton sendMailButton = new JButton("Send E-mail");
sendMailButton.addActionListener(new SendEmailActionListener());
footerPanel.add(sendMailButton, BorderLayout.SOUTH);
getContentPane().add(headerPanel, BorderLayout.NORTH);
getContentPane().add(bodyPanel, BorderLayout.CENTER);
getContentPane().add(footerPanel, BorderLayout.SOUTH);
}
private class SendEmailActionListener implements ActionListener {
SendEmailActionListener() {
}
@Override
public void actionPerformed(ActionEvent e) {
Properties props = new Properties();
props.put("mail.smtp.host", mailSmtpHostComboBox.getSelectedItem());
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
Session session = Session.getDefaultInstance(props);
try {
InternetAddress fromAddress = new InternetAddress(fromField.getText());
InternetAddress toAddress = new InternetAddress(toField.getText());
Message message = new MimeMessage(session);
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subjectField.getText());
message.setText(contentTextArea.getText());
Transport.send(message, usernameField.getText(),
new String(passwordField.getPassword()));
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Thanks. It was helpful.
Transport.send() is not working
Hi Rashid, what is the actual errors message that you got? Exception stack trace will be helpful to find out what causing the error was.
Please help with this error:
The error message in
Transport.send()
is: No suitable method found forTransport.send(Message, string, string)
. There is another methodTransport.send(message, addresses)
in thejavax.mail.Transport
but that does not match the number of parameters.Hi Learner, make sure you are using
javax.mail-api-1.5.x.jar
.Now I’m using
javax.mail-api-1.5.2.jar
. No compilation error. But when running getting exception:Hi again, you also need to include the
mail-1.4.7.jar
.Thank you so much.
You are welcome.
Hi Bro 🙂
First of all, thank you.
Second, I have a problem.
Trasport.send()
isn’t working.So,
Moreover, I updated
mail-1.4.7.jar
.Hello,
The
Transport.send(Message msg, String user, String password)
was added injavax.mail-api-1.5.jar
. So in addition tomail-1.4.7.jar
, you also need to use thejavax.mail-api-1.5.x.jar
. In my case I use the1.5.6
version ofjavax.mail-api
.The main problem is jar files how to download and how to link jar file to the java.
Hi Shruthi,
You can create a simple Maven application and add the dependencies listed above to your Maven
pom.xml
file. If you don’t use Maven, just download the jar from the link provided above and add it to your project library in your IDE.Hi, if it is possible, can you help me about my project. I create email system in Java SE GUI. I save all mails in
messageList
. And I have 2 lists. One of them is inbox, the other one is sentbox. But when I send a message, who is receiver see the message if him/her outbox. But it have to be in inbox. How can I fix it?How can I solve this?
I am unable to send the file help me to send the file
Hi Kavya,
Check the following example: How do I send an email with attachment?.
Hi, just wondering if this still works with gmail? Knowing google’s anti-competitive behavior in barring other mail clients (like KMail) I wouldn’t be surprised if it didn’t. If that’s correct, you might wanna update the tutorial on how to enable “legacy” access to gmail accounts. Cheers!