Java Send Email Tutorial
To send email using Java is very simple, but you must have the Application Programming Interface (API) and the Java Activation Framework (JAF). That’s how the Java send email works.
-
You can download the JAF here.
Download and unzip the file. You only need the activation.jar and javax.mail.jar to add to your library.
How to send email using Java
Example code
import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mail_API { String host = "smtp.gmail.com"; String sender = "[email protected]"; String password = "your email password"; public void SendMailAPI() { Properties prop = new Properties(); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.host", host); prop.put("mail.smtp.port", "587"); Session session = Session.getInstance(prop, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sender, password); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Test Subject"); message.setText("This is a message"); Transport.send(message); System.out.println("Message Sent"); } catch (Exception e) { System.out.println(e); } } }
Possible Error
If your Java application doesn’t run because of this error “username and password not accepted“. You must activate the Less secure app access in your Google Account. To fix this, go to your Google Account / Security / Less Secure App Access. Activate the Less secure app access to successfully run your Java application.