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 ''. 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:

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

public class SendMail
  private static final String SMTP_HOST_NAME = "";
  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;
            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("", SMTP_HOST_NAME);
     props.put("mail.smtp.auth", "true");

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


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

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

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

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

    // Setting the Subject and Content Type
    msg.setContent(message, "text/plain");

* 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