How to send an e-mail using Java Mail API (Swing Desktop Application using Google’s SMTP Server)


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

To use the Java Mail API inside your project, you should download the latest Java Mail API jar from the following link;

Java Mail API 1.4.4 Download

You should have a reference for the mail.jar inside the project and you can use the following source code for sending e-mail from Java Programs.


private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {

boolean isSent = true;

try {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", txtfrom.getText()); //such as abc@gmail.com
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", txthostName.getText());   //use smtp.google.com for Google
        properties.put("mail.smtp.user", txtfrom.getText()); //such as abc@gmail.com
        properties.put("mail.smtp.port", txtPort.getText()); //use 465 for Google's SMTP server
        properties.put("mail.smtp.socketFactory.port", txtPort.getText()); //use 465 for Google's SMTP server
        properties.put("mail.smtp.starttls.enable","true");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");

        Authenticator mailAuthenticator = new MailAuthenticator();
        Session mailSession = Session.getDefaultInstance(properties,mailAuthenticator);
        Message message = new MimeMessage(mailSession);

        InternetAddress fromAddress = new InternetAddress(txtfrom.getText());
        InternetAddress toAddress = new InternetAddress(txtto.getText());

        message.setFrom(fromAddress);
        message.setRecipient(RecipientType.TO, toAddress);
        //you can use RecipientTypes such as
        //RecipientType.TO
        //RecipientType.BCC
        //RecipientType.CC
        //RecipientType.NEWSGROUPS
        message.setSubject(txtsubject.getText());
        message.setText(txtcontent.getText());

        Transport.send(message);

} catch (Exception e) {
     lblInfo.setText("ERROR:" + e.getMessage());
     isSent = false;
}

     if(isSent == true) {
     sendButton.setEnabled(false);
     lblInfo.setText("Your e-mail has been sent.");
}

}

private class MailAuthenticator extends javax.mail.Authenticator {

private PasswordAuthentication authentication = null;
private String username;
private String password;

public MailAuthenticator() {
this.username = txtusername.getText();
this.password = new String(txtPassword.getPassword());
this.authentication = new PasswordAuthentication(username,password);
}

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

The following program uses Authentication before sending e-mails.

The screenshot for the program;

Download Source of the Program (Swing Java Mail API example program)

After downloading the program, you should  click on the .jar file under the following directory

Desktop\SendEmailJavaDesktopExample\SendEmailJavaDesktopExample\dist\SendEmailJavaDesktopExample.jar

Advertisements

How to set look and feel on Java Swing applications


Use the method setLookAndFeel like the following to change Java Swing applications’ appearance

try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch (Exception ex) {
//Just print stacktrace here since it's an example.
ex.printStackTrace();
}

And if you get an exception like the following one while trying to integrate SyntheticaStandardLookAndFeel for your application;

java.text.ParseException: Error parsing: org.xml.sax.SAXException: bind: unknown type REGİON null
    at javax.swing.plaf.synth.SynthParser.parse(SynthParser.java:230)
    at javax.swing.plaf.synth.SynthLookAndFeel.load(SynthLookAndFeel.java:589)
    at de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.loadXMLConfig(SyntheticaLookAndFeel.java:401)
    at de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.<init>(SyntheticaLookAndFeel.java:339)
    at de.javasoft.plaf.synthetica.SyntheticaStandardLookAndFeel.<init>(SyntheticaStandardLookAndFeel.java:30)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at javax.swing.UIManager.setLookAndFeel(UIManager.java:558)
    at examples.WelcomeForm.main(WelcomeForm.java:246)

You should change your current locale to English before setting Look and Feel like the code below;

Locale.setDefault(Locale.ENGLISH);
try {
UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaStandardLookAndFeel");
} catch (Exception ex) {
//Just print stacktrace here since it's an example.
ex.printStackTrace();
}

example Look and Feel class names;

javax.swing.plaf.metal.MetalLookAndFeel
com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
com.sun.java.swing.plaf.motif.MotifLookAndFeel
com.sun.java.swing.plaf.windows.WindowsLookAndFeel
com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel