In this tutorial we will see how to send email using Java Mail API. We are using Gmail SMTP host for sending email in the below sample code.
Mainly we need 2 jar files to implement Java Mail API. Those jar's are
- activation-1.0.2.jar
- mail-1.4.1.jar
Below code have tested along with above jar files.
import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; 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 SendEmailViaGmail { public static void main(String[] args) { // To address String to = "to@gmail.com"; // If any CC email ids String cc = "cc@abcmail.com"; // If any BCC email ids String bcc = "bcc@abcmail.com"; // Email Subject String subject = "Java Discover"; // Email content String emailText = "Hi All, Welcome to Java Discover"; // Sending Email using Gmail SMTP sendEmail(to, cc, bcc, subject, emailText); } public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) { // From address (Need Gmail ID) String from = "from@gmail.com"; // Password of from address String password = "frompassword"; // Gmail host address String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.user", from); props.put("password", password); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress(from)); // Adding To address msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); // Adding CC email id msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); // Adding BCC email id msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); msg.setText(emailText); Transport transport = session.getTransport("smtp"); transport.connect(host, from, password); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); System.out.println("Email sent successfully....."); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
IMP:
Suppose if you are getting exception while running above like,
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
then valid SSL certificate is missing in the machine which your running. Follow the steps given in link and try again.