Sending mail using java mail API
Java Mail API is a platform and protocol independent framework to send mail. It supports JDK 1.4 and above. It supports IMAP, POP3 and SMTP protocol. To use Java Mail API we have to include javax.mail.jar in your class library.
1 2 3 4 5 6 7 | <dependencies> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> </dependencies> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendMail { public static void main(String args[]) throws Exception { String host = "smtp.gmail.com"; String pass = "password"; String port = "587"; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); // required for gmail props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); InternetAddress toAddress = new InternetAddress(); toAddress = new InternetAddress(to); System.out.println(Message.RecipientType.TO); message.addRecipient(Message.RecipientType.TO, toAddress); message.setSubject("Hello"); message.setText("How are you"); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Mail Sent successfully"); } } |
for this java mail api should be present on your class path.