Thursday, May 30, 2013

How to send mail in java

package com.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class Send_Email
{
/**
* author Mayur Laniya
**/
   public static void main(String [] args)
   {   
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system port
     // String post = "9090";
      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 s = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("to email id","your password");
                    }
                  });
      MimeMessage msg = new MimeMessage(s);
      try
      {
          msg.setFrom(new InternetAddress("to email id"));
          msg.addRecipient(Message.RecipientType.TO,new InternetAddress("from mail id"));
          msg.setSubject("wel come");
          msg.setText("Goood day");
          Transport.send(msg);
          System.out.println("msg sucessfully sent");
         
         
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }
    

    
    
   }
}

No comments:

Post a Comment