skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Thursday, September 20, 2012

Email Services

Posted by Admin at 12:17 PM – 0 comments
 

Email utility code though which we can send and receive mails via java api.


import java.security.Security;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestTemp {

 private Logger log = Logger.getLogger(getClass());
 
 private static final String SMTP_HOST_NAME = "xxx@yyy.zzz";
 private static final String SMTP_PORT = "465";
 private static final String AUTH_USER_ID="username";
 private static final String AUTH_USER_PWD="password";
 private static final String SSL_SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
 
 public static void main(String[] args) throws Exception {
  TestTemp tmp = new TestTemp();
    
  Session session = null;
  try{
   session = tmp.getMailSession();
   
   javax.mail.Message msg = new MimeMessage(session);
   InternetAddress addressFrom = new InternetAddress(AUTH_USER_ID);
   msg.setFrom(addressFrom);
   
   InternetAddress addressTo = new InternetAddress("to_email_id");
   msg.setRecipient(Message.RecipientType.TO, addressTo);
   msg.setSubject("testing subject");
   msg.setText("sample mail body");
   Transport.send(msg);
   
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public Session getMailSession(){
  Properties props = null;
  Session session = null;

  try{
   props = setMailProperties();

   session = Session.getInstance(props,
     new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(AUTH_USER_ID, AUTH_USER_PWD);
    }
   });
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return session;
 }

 public Properties setMailProperties()
 {

  Properties props = new Properties();

  // Setting SMTP properties
  props.put("mail.smtp.host", SMTP_HOST_NAME);
  props.put("mail.smtp.user", AUTH_USER_ID);
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", SMTP_PORT);
  props.put("mail.smtp.socketFactory.port", SMTP_PORT);
  props.put("mail.smtp.socketFactory.class", SSL_SOCKET_FACTORY);
  props.put("mail.smtp.ssl.enable","true");
  props.put("mail.transport.protocol", "smtp");

  return props;
 }
}



Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger