Archive

Posts Tagged ‘mail’

Java Code to Receive Mail using JavaMailAPI

March 21, 2010 35 comments

Introduction:

In the previous article, we have looked at sending mail with Java Mail API.Sending e-mail was relatively simple with only one protocol (SMTP) to handle. But Reception involves two protocols, POP3 and IMAP. POP3 is the older protocol, which offers a single queue of mail messages as a single inbox. IMAP is the more modern protocol, which presents mail messages as entries in a hierarchy of folders, one of which will be an inbox.

Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.

Prerequisites:

JDK 1.5 and Above

Jar: Mail. jar

Steps involved in receive mail:

Step 1: Define the mail properties (i.e.) Define the protocol, mail server by using the properties class.

Step 2: Create the session for read the mail with the properties which we already defined.

Step 3: Create and connect the store for read the mail.

Step 4: Define and open the folder which we need to read. Open the folder in read-only mode.

Step 5: Search the unread contents in the specified folder and stored it into messages array.

Step 6: Display the messages.

Description of classes and methods :

Store:

An abstract class that models a message store and its access protocol, for storing and retrieving messages.

Methods:

connect -> It is used to connect the store with the mail server store.

getFolder-> It is used to define the folder which will be read. Return Folder class.

Folder:

Folder is an abstract class that represents a folder for mail messages. Folders can contain Messages, other Folders

Methods:

open   -> Method for open the foder.We must define the mode of open.

search -> Method for get the messages. Return type: Message[].

fetch  -> Method for Fetch the details which is represented by FetchProfile.

close  -> Method for close the folder.

FetchProfile:

List the Message attributes that it wishes to prefetch from the server for a range of messages.

Method:

add  ->  Method for add the attributes which we wish to prefetch.

Message:

This class models an email message. This is an abstract class. Message implements the Part interface

A Message object obtained from a folder is just a lightweight reference to the actual message.

Methods:

getContent  ->  Method for get the content of the message.

Code:

/*
 *  This is the code for read the unread mails from your mail account.
 *  Requirements:
 *      JDK 1.5 and above
 *      Jar:mail.jar
 *
 */
package com.info.mail;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class MailReader
{
 Folder inbox;

 //Constructor of the calss.
 public MailReader()
 {
 /*  Set the mail properties  */
 Properties props = System.getProperties();
 props.setProperty("mail.store.protocol", "imaps");
 try
 {
 /*  Create the session and get the store for read the mail. */
 Session session = Session.getDefaultInstance(props, null);
 Store store = session.getStore("imaps");
 store.connect("imap.gmail.com","<mail ID> ", "<Password>");

 /*  Mention the folder name which you want to read. */
 inbox = store.getFolder("Inbox");
 System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());

 /*Open the inbox using store.*/
 inbox.open(Folder.READ_ONLY);

 /*  Get the messages which is unread in the Inbox*/
 Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));

 /* Use a suitable FetchProfile    */
 FetchProfile fp = new FetchProfile();
 fp.add(FetchProfile.Item.ENVELOPE);
 fp.add(FetchProfile.Item.CONTENT_INFO);
 inbox.fetch(messages, fp);

 try
 {
 printAllMessages(messages);
 inbox.close(true);
 store.close();
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at the time of read mail");
 ex.printStackTrace();
 }
 }
 catch (NoSuchProviderException e)
 {
 e.printStackTrace();
 System.exit(1);
 }
 catch (MessagingException e)
 {
 e.printStackTrace();
 System.exit(2);
 }
 }

 public void printAllMessages(Message[] msgs) throws Exception
 {
 for (int i = 0; i < msgs.length; i++)
 {
 System.out.println("MESSAGE #" + (i + 1) + ":");
 printEnvelope(msgs[i]);
 }
 }

 /*  Print the envelope(FromAddress,ReceivedDate,Subject)  */
 public void printEnvelope(Message message) throws Exception
 {
 Address[] a;
 // FROM
 if ((a = message.getFrom()) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("FROM: " + a[j].toString());
 }
 }
 // TO
 if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("TO: " + a[j].toString());
 }
 }
 String subject = message.getSubject();
 Date receivedDate = message.getReceivedDate();
 String content = message.getContent().toString();
 System.out.println("Subject : " + subject);
 System.out.println("Received Date : " + receivedDate.toString());
 System.out.println("Content : " + content);
 getContent(message);
 }

 public void getContent(Message msg)
 {
 try
 {
 String contentType = msg.getContentType();
 System.out.println("Content Type : " + contentType);
 Multipart mp = (Multipart) msg.getContent();
 int count = mp.getCount();
 for (int i = 0; i < count; i++)
 {
 dumpPart(mp.getBodyPart(i));
 }
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at get Content");
 ex.printStackTrace();
 }
 }

 public void dumpPart(Part p) throws Exception
 {
 // Dump input stream ..
 InputStream is = p.getInputStream();
 // If "is" is not already buffered, wrap a BufferedInputStream
 // around it.
 if (!(is instanceof BufferedInputStream))
 {
 is = new BufferedInputStream(is);
 }
 int c;
 System.out.println("Message : ");
 while ((c = is.read()) != -1)
 {
 System.out.write(c);
 }
 }

 public static void main(String args[])
 {
 new MailReader();
 }
}

Advertisements

Java code sending Mail with Attachment using Java Mail API

March 3, 2010 39 comments

Introduction

In a day-to-day life the emails are occupied our life.If we can send our mails by using our java code without help of browser how we feel?

This article do this.By using the JavaMail API send our mail with attachment without help of browser.This code need a mail.jar file.You can download this at http://www.java2s.com/Code/Jar/JKL/Downloadmailjar.htm


Code:


/ * This code is only for design the frame
 *
 * @author muneeswaran
 */
package com.mail;

import javax.mail.MessagingException;
import javax.swing.*;

public class MailSender extends JFileChooser
{

    private JTextField attachmentTextField;
    private JLabel jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, jLabel6;
    private JScrollPane jScrollPane1;
    private JTextArea messageTextArea;
    private JButton sendButton, cancelButton, browseButton;
    private JTextField ccTextField, subjectTextField, toTextField;
    String toAddress = null, ccAddress = null, message = null,
            receipientsList[] = null, attachments[] = null, receipients, subject;
    String fromAddress = "put your full mail id"; //Place your mail id here.
    String authenticationPassword = "your password";//Place your password here

    public MailSender()
    {
        initComponents();
    }

    private void initComponents()
    {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel("To");
        toTextField = new javax.swing.JTextField(20);
        jLabel3 = new javax.swing.JLabel("CC");
        ccTextField = new javax.swing.JTextField(20);
        jLabel4 = new javax.swing.JLabel("Subject");
        subjectTextField = new javax.swing.JTextField(20);
        jLabel5 = new javax.swing.JLabel("Attachemnet");
        attachmentTextField = new javax.swing.JTextField(20);
        browseButton = new javax.swing.JButton("Browse");
        jLabel6 = new javax.swing.JLabel("Message");
        jScrollPane1 = new javax.swing.JScrollPane();
        messageTextArea = new javax.swing.JTextArea(20, 10);
        sendButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        //setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("AlMateen-Bold", 3, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(1, 203, 221));
        jLabel1.setText("Mail Sender");
        jScrollPane1.setViewportView(messageTextArea);
        sendButton.setText("Send");
        sendButton.addActionListener(new java.awt.event.ActionListener()
        {

            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                sendButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener()
        {

            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                cancelButtonActionPerformed(evt);
            }
        });

        browseButton.addActionListener(new java.awt.event.ActionListener()
        {

            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                browseButtonActionPerformed(evt);
            }
        });

        jLabel1.setBounds(100, 50, 200, 50);
        jLabel2.setBounds(50, 100, 100, 50);
        toTextField.setBounds(150, 100, 300, 40);

        jLabel3.setBounds(50, 150, 100, 50);
        ccTextField.setBounds(150, 150, 300, 40);

        jLabel4.setBounds(50, 200, 100, 50);
        subjectTextField.setBounds(150, 200, 300, 40);

        jLabel5.setBounds(50, 250, 100, 50);
        attachmentTextField.setBounds(150, 250, 200, 40);
        browseButton.setBounds(375, 250, 100, 20);

        jLabel6.setBounds(50, 300, 100, 50);
        messageTextArea.setBounds(150, 300, 300, 40);

        sendButton.setBounds(100, 400, 75, 20);
        cancelButton.setBounds(200, 400, 75, 20);
        JFrame mailFrame = new JFrame("Mail Sender");
        mailFrame.add(jLabel1);
        mailFrame.add(jLabel2);
        mailFrame.add(toTextField);
        mailFrame.add(jLabel3);
        mailFrame.add(ccTextField);
        mailFrame.add(jLabel4);
        mailFrame.add(subjectTextField);
        mailFrame.add(jLabel5);
        mailFrame.add(attachmentTextField);
        mailFrame.add(browseButton);
        mailFrame.add(jLabel6);
        mailFrame.add(messageTextArea);
        mailFrame.add(sendButton);
        mailFrame.add(cancelButton);

        mailFrame.setLayout(null);
        mailFrame.setVisible(true);
        mailFrame.setSize(500, 500);
        mailFrame.setResizable(false);
        mailFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        // TODO add your handling code here:
    }

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        JFileChooser selectFile = new JFileChooser();
        selectFile.showOpenDialog(this);
        attachmentTextField.setText(selectFile.getSelectedFile().toString());
    }

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt)
    {

        toAddress = toTextField.getText().trim();
        ccAddress = ccTextField.getText().trim();
        subject = subjectTextField.getText().trim();
        message = messageTextArea.getText().trim();
        String attachment = attachmentTextField.getText() + " ";

        attachments = attachment.split(" ");

        receipients = toAddress + "," + ccAddress;
        receipientsList = receipients.split(",");

        SendMailUsingAuthentication mailUsingAuthentication =
                new SendMailUsingAuthentication();
        try {
            mailUsingAuthentication.postMail(receipientsList,
                    subject, message, fromAddress, authenticationPassword, attachments);
        } catch (MessagingException messagingException) {
            messagingException.printStackTrace();
        }
    }

    void login(String userName, String password)
    {
        fromAddress = userName;
        authenticationPassword = password;
        System.out.println("User name : " + fromAddress);
    }

    public static void main(String[] args)
    {
        new MailSender();
    }
}

This is the Code for send Mail with attachment


/* This code is used for send the mail to the any users.</div>
 * It is done by Java Mail Api.
 * By using this code we can send mail with out enter into your mail Account.
 * @author muneeswaran
 */
package com.mail;

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

public class SendMailUsingAuthentication {

    private String HOST_NAME = "gmail-smtp.l.google.com";
    String messageBody;

    public void postMail(String recipients[], String subject, String message,
            String from, String emailPassword, String[] files) throws MessagingException {
        boolean debug = false;
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator authenticator = new SMTPAuthenticator(from, emailPassword);
        Session session = Session.getDefaultInstance(props, authenticator);

        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[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

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

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);

        Multipart multipart = new MimeMultipart();

        //add the message body to the mime message
        multipart.addBodyPart(messageBodyPart);

        // add any file attachments to the message
        addAtachments(files, multipart);
        //Put all message parts in the message
        msg.setContent(multipart);
        Transport.send(msg);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    protected void addAtachments(String[] attachments, Multipart multipart)
            throws MessagingException, AddressException {
        for (int i = 0; i <= attachments.length - 1; i++) {
            String filename = attachments[i];
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            //use a JAF FileDataSource as it does MIME type detection
            DataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            attachmentBodyPart.setFileName(filename);
            //add the attachment
            multipart.addBodyPart(attachmentBodyPart);
        }
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        String username;
        String password;

        private SMTPAuthenticator(String authenticationUser, String authenticationPassword) {
            username = authenticationUser;
            password = authenticationPassword;
        }

        @Override
        public PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);
        }
    }
}