Pages

Ads 468x60px

Sunday, July 22, 2012

Java: Send Email

This program can be used to send email using yahoo smtp client. If you want to use Gmail client then try 'smtp.gmail.com'. I have used mail.jar for this purpose. Please include this JAR file in your project to run this program. You can download this jar from the following link: http://mvnrepository.com/artifact/javax.mail/mail/1.4





import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendMail
{
  private static final String SMTP_HOST_NAME = "smtp.mail.yahoo.com";
  private static final String SMTP_AUTH_USER = "Your Email Address here";
  private static final String SMTP_AUTH_PWD  = "Your Email password here";

  private static String emailMsgTxt = "Your Message Text";
  private static final String emailSubjectTxt  = "Your Subject Text";
  private static final String emailFromAddress = "Your Email Address here";

  public boolean sendMail(String emailTo)
  {
      boolean sent = false;
      try{
            SendMail smtpMailSender = new SendMail();
            smtpMailSender.postMail( emailTo, emailSubjectTxt, emailMsgTxt, emailFromAddress);
            sent = true;
      }
    catch(Exception ex){
        System.out.println("Error in sending mail to user.");
    }
      return sent;
  }

  private void postMail( String recipients, String subject,
                            String message , String from) throws MessagingException
  {
    boolean debug = false;
     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", SMTP_HOST_NAME);
     props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[1];
    addressTo[0] = new InternetAddress(recipients);

    msg.setRecipients(Message.RecipientType.TO, addressTo);


    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
 }

/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/

private class SMTPAuthenticator extends javax.mail.Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        String username = SMTP_AUTH_USER;
        String password = SMTP_AUTH_PWD;
        return new PasswordAuthentication(username, password);
    }
}
}

No comments:

Post a Comment