Saturday, 18 January 2014

Send EMail

How to send e-mail using java :


Hey Friends, Welcome again !!! Today I will show you how to send an e-mail using java. This post will help you in sending emails to anyone using a simple java code.

To use the code you must have to set the classpath of the given jar file named mail.jar which contains the library for the given code. You can download the jar file from the link given below.
1. mail.jar

After downloading the jar file, set the classpath of the jar file so that we can use it and then use the code given below:

SendEmail.java :


 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 SendEmail {  
    
      public static void main(String[] args) {  
    
           final String username = "sender-email-id@gmail.com";  
           final String password = "password";  
    
           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");  
           props.put("mail.smtp.port", "587");  
    
           Session session = Session.getInstance(props,  
            new javax.mail.Authenticator() {  
             @Override  
                protected PasswordAuthentication getPasswordAuthentication() {  
                     return new PasswordAuthentication(username, password);  
                }  
            });  
    
           try {  
    
                Message message = new MimeMessage(session);  
                message.setFrom(new InternetAddress("sender-email-id@gmail.com"));  
                message.setRecipients(Message.RecipientType.TO,  
                     InternetAddress.parse("receiver-email-id@gmail.com"));  
                message.setSubject("Testing");  
                message.setText("Email sent using java..."  
                     + "\n\n Stay tuned to tutorialsonadvancejava.blogspot.in");  
    
                Transport.send(message);  
    
                System.out.println("Done");  
    
           } catch (MessagingException e) {  
                throw new RuntimeException(e);  
           }  
      }  
 }  

In the above code, use the valid email id and password so that the code validate it from the internet and send your mail.

Now compile the above code using valid email id and password the run it to send the email.

I hope you will find this post helpful in various JAVA Projects. If you face any difficulty in this post you can ask it by commenting here. i will reply as soon as possible.

For more java codes................ stay connected  :-)