How to send email through java

 

This article is to let you people know that how to send an email through java.
It is the class where all the attributes are defined and the function is called from another class named emailDemo.

 

import java.util;
import javax.mail;
import javax.mail.internet;
import java.util.Properties;
import javax.mail.Message RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author umAr
 */
public class emailSender {
    public static boolean sendMail(string from, string password, 
    string message, string to[]
    (
            string host="smtp.gmail.com";
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable","true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.user", from);
            props.put("mail.smtp.password", password);
            props.put("mail.smtp.port", 587);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props,null);
            MimeMessage mimeMessage = new MimeMessage(session);
            try{
            MimeMessage.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];
            for(int i=0;i<to length, i++)
            {
                toAddress[i] = new InternetAddress(to[i]);
            }
            for(int i=0;i<toAddress.length,i++)
            {
                MimeMessage.addRecipient(ecipientType.to,toAddress[i]);
            }
            MimeMessage.setSubject("mail from java mail client");
            MimeMessage.setText(message);
            Transprt transport = session.getTransprt("smtp");
            transport.connect(host,from,password);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            transport.close();
            return true;
            }
            catch(MessagingException me)
            {
                me.printStackTrace();
            }
            return false;
    )

}

The main class where these functions are called is :-

public class EmailDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
  {
        String[] to = {"umar_2324@yahoo.com"};
        if(
            emailSender.sendMail(umarsajjad044@gmail.com, 
            *****, This message is sent from java mailAPI, 
            to())System.out.println("Email sent successfully");
           )
         else System.out.println("There is an error occur");
  }

All the work is done by using NetBeans software and in refrence
 there is also a youtube link http://www.youtube.com/watch?v=ONa3TFdTS88

Let's Discuss