skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, October 13, 2012

This code can be used in any java application to send mails

Posted by Raju Gupta at 12:00 PM – 0 comments
 

Attached jar file (EmailSender v1.0) can be used in any Java/J2EE application to send authenticated as well as non authenticated mails. Jar supporting only 4 free smtp hosts.
1. Gmail (smtp.gmail.com)
2. Yahoo (smtp.mail.yahoo.com)
3. Rediff (smtp.rediffmail.com)
4. HotMail (smtp.live.com)
This jar file can be used as a stand alone application or can be integrated with any J2EE application.

import java.io.BufferedReader;   
import java.io.File;   
import java.io.IOException;   
import java.io.InputStreamReader;   
import java.io.RandomAccessFile;   
import java.util.ArrayList;   
import java.util.Date;   
import java.util.Properties;   
import java.util.StringTokenizer;   
  
import javax.activation.DataHandler;   
import javax.activation.DataSource;   
import javax.activation.FileDataSource;   
import javax.mail.Address;   
import javax.mail.Authenticator;   
import javax.mail.Message;   
import javax.mail.MessagingException;   
import javax.mail.Multipart;   
import javax.mail.PasswordAuthentication;   
import javax.mail.SendFailedException;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeBodyPart;   
import javax.mail.internet.MimeMessage;   
import javax.mail.internet.MimeMultipart;   
import javax.mail.util.ByteArrayDataSource;   
  
public class EmailManager   
{   
    private String AUTH_USER_NAME;   
    private String AUTH_PWD;   
    private String SMTP_HOST;   
    private String SMTP_PORT;   
  
           
    public void sendEmailWithAuthentication(String filePath, String strFromEmailId, String strToEmailId, String strEmailSubject, String fileAttachment) throws Exception   
    {   
        StringBuilder strFileText = new StringBuilder("");   
  
        try  
        {   
  
            try  
            {   
                if(filePath != null)   
                {   
                    File textFile = new File(filePath);   
                    RandomAccessFile rendFile = new RandomAccessFile(textFile, "r");   
       
                    while (rendFile.getFilePointer() < rendFile.length())   
                    {   
                        strFileText.append("\n").append(rendFile.readLine());   
                    }   
                }   
            }   
            catch (Exception e)   
            {   
                System.err.println("Could not find file: " + e);   
                e.printStackTrace();   
            }   
  
            boolean debug = Boolean.valueOf("true").booleanValue();   
  
            Properties props = new Properties();   
            props.put("mail.smtp.host", SMTP_HOST);   
            props.put("mail.smtp.auth", "true");   
            props.put("mail.debug", "true");   
            props.put("mail.smtp.port", SMTP_PORT);   
            props.put("mail.smtp.starttls.enable","true");   
            props.put("mail.smtp.socketFactory.port", SMTP_PORT);    
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");    
            props.put("mail.smtp.socketFactory.fallback", "false");    
  
            Authenticator auth = new SMTPAuthenticator();//Added 4 authentication   
               
            Session session = Session.getDefaultInstance(props, auth);   
            session.setDebug(debug);   
  
            Message msg = new MimeMessage(session);   
  
            msg.setDataHandler(new DataHandler(new ByteArrayDataSource(strFileText.toString(), "text/plain")));   
            msg.setFrom(new InternetAddress(strFromEmailId));   
  
            // create the message part    
            if(fileAttachment != null)   
            {   
                MimeBodyPart messageBodyPart = new MimeBodyPart();   
                messageBodyPart.setText(strFileText.toString());   
                   
                Multipart multipart = new MimeMultipart();   
                multipart.addBodyPart(messageBodyPart);   
                messageBodyPart = new MimeBodyPart();   
                DataSource source = new FileDataSource(fileAttachment);   
                messageBodyPart.setDataHandler(new DataHandler(source));   
                messageBodyPart.setFileName(fileAttachment);   
                multipart.addBodyPart(messageBodyPart);   
                msg.setContent(multipart);   
            }   
               
               
            StringTokenizer strtok = new StringTokenizer(strToEmailId, ",");   
            String subStrToEmailId[] = new String[strtok.countTokens()];   
            int countToMail = 0;   
            while (strtok.hasMoreTokens())   
            {   
                subStrToEmailId[countToMail] = strtok.nextElement().toString().trim();   
                countToMail++;   
            }   
  
            for (int i = 0; i < subStrToEmailId.length; i++)   
            {   
  
                InternetAddress[] address = { new InternetAddress(subStrToEmailId[i]) };   
                msg.addRecipients(Message.RecipientType.TO, address);   
            }   
  
            msg.setSubject(strEmailSubject);   
            Date dt = new Date();   
            msg.setSentDate(dt);   
            System.out.println("Before sending message... ");   
            Transport.send(msg);   
            System.out.println("After sending message... ");   
        }   
        catch (MessagingException mex)   
        {   
            System.out.println("\n--Exception handling in msgsendsample.java");   
  
            mex.printStackTrace();   
            System.out.println();   
            Exception ex = mex;   
            do  
            {   
                if (ex instanceof SendFailedException)   
                {   
                    SendFailedException sfex = (SendFailedException) ex;   
                    Address[] invalid = sfex.getInvalidAddresses();   
                    if (invalid != null)   
                    {   
                        System.out.println("    ** Invalid Addresses");   
                        if (invalid != null)   
                        {   
                            for (int i = 0; i < invalid.length; i++)   
                                System.out.println("         " + invalid[i]);   
                        }   
                    }   
                    Address[] validUnsent = sfex.getValidUnsentAddresses();   
                    if (validUnsent != null)   
                    {   
                        System.out.println("    ** ValidUnsent Addresses");   
                        if (validUnsent != null)   
                        {   
                            for (int i = 0; i < validUnsent.length; i++)   
                                System.out.println("         " + validUnsent[i]);   
                        }   
                    }   
                    Address[] validSent = sfex.getValidSentAddresses();   
                    if (validSent != null)   
                    {   
                        System.out.println("    ** ValidSent Addresses");   
                        if (validSent != null)   
                        {   
                            for (int i = 0; i < validSent.length; i++)   
                                System.out.println("         " + validSent[i]);   
                        }   
                    }   
                }   
                System.out.println();   
                if (ex instanceof MessagingException)   
                    ex = ((MessagingException) ex).getNextException();   
                else  
                    ex = null;   
            }   
            while (ex != null);   
        }   
  
        catch (Exception e)   
        {   
            System.err.println("Error Message: " + e.getMessage());   
        }   
    }   
       
       
       
    private class SMTPAuthenticator extends Authenticator {   
        public PasswordAuthentication getPasswordAuthentication() {   
           String username = AUTH_USER_NAME;   
           String password = AUTH_PWD;   
           return new PasswordAuthentication(username, password);   
        }   
    }   
}  


Labels: Email Example , Java Mail Examples

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