The need to send Email in Java would be one of the most common requirements in many of the Java applications. Fortunately, the Java Mail API makes this possible with very less effort. The Java Mail API is not part of the JDK, it is an optional package. Oracle provides the reference implementation of the Java Mail API which you can use and ship as part of your application. The Java Mail API is part of the JEE platform.
Below is the sample code to send email in Java using Java Mail API,
package com.mjc.email; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class JavaMail { public static final String SMTP_HOST = "smtp.gmail.com"; public static final String SMTP_PORT = "587"; public static final String USER_NAME = "developerteam2.1@gmail.com"; public static final String PASSWORD = "developer123"; public static void main(String[] args) throws AddressException, javax.mail.MessagingException { String emailBody = "Email Content Here ...<b>Bold Text Here</b>"; String emailSubject = "Email Subject Here"; sendEmail("developerteam2.1@gmail.com", "prasanna.lm@i-exceed.com", emailSubject, emailBody); } private static void sendEmail(String fromAddress, String toAddress, String subject, String emailBody) throws MessagingException { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", SMTP_HOST); props.put("mail.smtp.port", SMTP_PORT); // this would be required only if TLS is enabled on the SMTP server props.put("mail.smtp.starttls.enable", "true"); // useful for debugging as this would log additional information props.put("mail.debug", "true"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USER_NAME, PASSWORD); } }); // Create a MimeMessage object. MimeMessage mimeMessage = new MimeMessage(session); // Set From email address. mimeMessage.setFrom(new InternetAddress(fromAddress)); // Set To email address. mimeMessage.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(toAddress)); // Set email Subject mimeMessage.setSubject(subject); // set the email body mimeMessage.setContent(emailBody, "text/html"); // Send message Transport.send(mimeMessage); } }
In the above sample code, we are using Gmail SMTP Server for sending the emails. Instead, you can replace the same with your SMTP server related parameters.
Also Read: How to Check Free Disk Space in Java