Nov 26 2013
Send Email using Core Java
To send email using core java first of all you required JavaMail API in your computer. You can download lates version of JavaMail API.
Download and extract files from javamail-version.zip file. Here you will find mail.jar file. For successfully run below example you need to set CLASSPATH to this jar file.
Send Email using Core Java Sample Code
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | /*We must download mail.jar file from http://www.oracle.com/technetwork/java/javamail-1-4-140512.html Set classpath to mail.jar file */ import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail { public static void main(String[] args) { final String username = "yourusername@gmail.com"; // User name required for authentication final String password = "Password"; // Password required for authentication Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); // host address of SMTP mail server //Here we are sending mail using Gmail thats why smtp.gmail.com props.put("mail.smtp.port", "587"); //port number of SMTP mail server //Create session on SMTP mail server using Username and Password Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { //Create new Email Message newmail = new MimeMessage(session); //From address which will display in actual mail. This is not authentication email address. newmail.setFrom(new InternetAddress("vimal.ghorecha@gmail.com")); //To whom we want to send email newmail.setRecipients(Message.RecipientType.TO,InternetAddress.parse("vimal6119@yahoo.com")); //For multiple recipients //newmail.setRecipients(Message.RecipientType, Array of InternetAddresss); //Subject Text of mail. newmail.setSubject("Testing Subject"); //Body of the mail newmail.setText("Dear Vimal Ghorecha," + "\n\n This is testing mail!"); Transport.send(newmail); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } } |
javac -cp “Path to mail.jar file” SendMail.java
Step 2 : Run SendMail with Java
java -cp “Path to SendMail.java;Path to mail.jar file” SendMail