Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

java code for accessing email attachments

Posted on 1999-07-16
4
Medium Priority
?
778 Views
Last Modified: 2013-11-24
How do i retrieve and add attachments to an email using POP3 and SMTP. Please give the java code required to do these two things.
0
Comment
Question by:srinivasavaradhan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 

Author Comment

by:srinivasavaradhan
ID: 1246278
I have written codes in java to send and receive mail using POP3 and SMTP.  But i don't know how to really access the attachments, how they can be recognized and the logic behind accessing them.  I dont want to work with any email clients.
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1246279
read the protocol specification carefully :)
or search the web.
I've seen at least one or two attachment examples.
0
 

Accepted Solution

by:
pgau061099 earned 400 total points
ID: 1246280
Hello,

  After had struggled a little bit with RFC and similar specifications, I got some idea that what is dealing directly with email protocols. And it's quite better, IMHO, than use something like the JavaMail package. Being aware of what happens in your code is always a positive thing.
  First, to send emails you need to connect to your mail server (you have to know the URL or IP) in the port 25 (standard for the mail servers). Then you just begin a SMTP session. There's a protocol for that, specified in RFC 821 (http://info.internet.isi.edu:80/in-notes/rfc/files/rfc821.txt). Following the correct steps, in the correct order, you can send a simple text message using this way.
  Second, there is the problem of ow to attach file to you message. And the answer is MIME, a extension to the Internet mail messages that allows you to embbed application files as printable caracaters. To achive this, you have to encode your file. The tecnique I used was the Base64, that has the drawback to be larger than the original file. Details in RFC1521.
  Third, you have to put all this things to work together. One away to do this is to get a sample mail and hard code it in your program. It's not straigthforward, but works.
  To ilustrate, some code. Hope it helps.


                        Best regards,

                          Paulo Urbano.


P.S: The most of the code belo was found in the Web. My work was just glue the whole thing together.

--------
// File Mail.java

import java.io.*;
import java.util.Vector;
import java.util.StringTokenizer;
import java.net.*;



class Mail {

  String subject;
  String att;
  String dirnomearq;
  String server;
  String rcp;
      
  Mail(String s, String nomearq, String dn, String serv, String recipient) {

    subject = s;
    this.att = nomearq;
    dirnomearq = dn;
    server = serv;
    rcp = recipient;

  }  

  public static void main(String args[]) {

    Mail prog = new Mail("Teste","teste.zip","/home/user/teste.zip",args[0],args[1]);
    prog.run();

  }

  public void run() {
   try {

    SMTPSession session = new SMTPSession(server,rcp,"noone@here.com");
    session.setMsg(readFile());
    session.sendMessage();
   } catch (Exception e) {

      System.out.println("Erro na conexao: "+e);
      
     }
 
  }

  String[] readFile() {

   String[] msg = null;

      
   Vector vec = new Vector();
   
   
   String aux= "From: Paulo Urbano <paulo@3onda.com.br>\n";
   aux += "MIME-Version: 1.0\n";
   aux += "To: "+this.rcp+"\n";
   aux += "Subject: Teste\n";
   aux += "Content-Type: multipart/mixed; boundary=\"------------7CFF779C1F326FE4B7272D88\"\n";
   aux += "This is a multi-part message in MIME format.\n";
   aux += "--------------7CFF779C1F326FE4B7272D88\n";
   aux += "Content-Type: text/html; charset=us-ascii\n";
   aux += "Content-Transfer-Encoding: 7bit\n\n\n";  
   aux += localLoad("/home/cip/cppu1232/index.html")+"\n";
   aux += "--------------7CFF779C1F326FE4B7272D88\n";
   aux += "Content-Type: application/zip; name=\""+att+"\"\n";
   aux += "Content-Transfer-Encoding: Base64\n";
   aux += "Content-Disposition: inline; filename=\""+att+"\"\n\n\n";
   

   vec.addElement(aux);

   Base64 bf = new Base64(dirnomearq);
   String[] st = bf.encode();
   int count = st.length;
   for (int i=0;i<count;i++) {
     vec.addElement(st[i]);
   }

   vec.addElement("--------------7CFF779C1F326FE4B7272D88--\n");

   msg = new String[vec.size()];

   for (int i=0;i<vec.size();i++) {
     msg[i] = (String)vec.elementAt(i);
   }

    return msg;

  }

  String localLoad(String arqname) {

        File dope;
        RandomAccessFile rdope;
        char[] carray;
        String res = " ";

        try {

            dope = new File(arqname);
            rdope = new RandomAccessFile(arqname,"r");
            carray = new char[(int)rdope.length()];
            InputStreamReader is = new InputStreamReader(new FileInputStream(dope));
            is.read(carray,0,carray.length);
            res = new String(carray);

        } catch (Exception e) {

            System.out.println("Erro: "+e);
          }

        return res;

      }


}



//File SMTPSession.java

import java.io.*;
import java.net.*;
import java.util.*;

public class SMTPSession extends Object
{
     public String host;     // Host name we connect to
     public int port;     // port number we connect to, default=25

     public String recipient;
     public String sender;
     public String[] message;

     protected Socket sessionSock;

     protected DataInputStream inStream;
     protected DataOutputStream outStream;

     public SMTPSession()
     {
     }

     public SMTPSession(String host, String recipient,
          String sender, String[] message)
     throws IOException
     {
          this.host = host;
          this.port = 25;     // default SMTP port is 25

          this.recipient = recipient;
          this.message = message;
          this.sender = sender;
     }

     public SMTPSession(String host, String recipient,
          String sender)
     throws IOException
     {
          this.host = host;
          this.port = 25;     // default SMTP port is 25

          this.recipient = recipient;
          this.sender = sender;
     }

     public SMTPSession(String host, int port, String recipient,
          String sender, String[] message)
     throws IOException
     {
          this.host = host;
          this.port = port;
          if (this.port <= 0) this.port = 25;

          this.recipient = recipient;
          this.message = message;
          this.sender = sender;
     }

// Set the message

     public void setMsg(String[] msg){

       message = msg;      

     }



// Close down the session


     public void close()
     throws IOException
     {
          sessionSock.close();
          sessionSock = null;
     }

// Connect to the server

     protected void connect()
     throws IOException
     {
          sessionSock = new Socket(host, port);
          inStream = new DataInputStream(
               sessionSock.getInputStream());
          outStream = new DataOutputStream(
               sessionSock.getOutputStream());
        print("Conectado ao servidor "+host);

     }

// Send a command and wait for a response

     protected String doCommand(String commandString)
     throws IOException
     {
          outStream.writeBytes(commandString+"\r\n");
          String response = getResponse();
          return response;
     }

// Get a response back from the server. Handles multi-line responses
// and returns them as part of the string.

     protected String getResponse()
     throws IOException
     {
          String response = "";

          for (;;) {
               String line = inStream.readLine();

               if (line == null) {
                    throw new IOException(
                         "Bad response from server.");
               }

// FTP response lines should at the very least have a 3-digit number

               if (line.length() < 3) {
                    throw new IOException(
                         "Bad response from server.");
               }
               response += line + "\r\n";

// If there isn't a '-' immediately after the number, we've gotten the
// complete response. ('-' is the continuation character for FTP responses)

               if ((line.length() == 3) ||
                    (line.charAt(3) != '-')) return response;
          }
     }


// Sends a message using the SMTP protocol

     public void sendMessage()
     throws IOException
     {
          connect();

// After connecting, the SMTP server will send a response string. Make
// sure it starts with a '2' (reponses in the 200's are positive
// responses.

          String response = getResponse();
          if (response.charAt(0) != '2') {
          print("At connect");
            throw new IOException(response);
          }

// Introduce ourselves to the SMTP server with a polite "HELO"
          response = doCommand("HELO pgau.interway.com.br");

          if (response.charAt(0) != '2') {
              print("At HELO");
               throw new IOException(response);
          }

// Tell the server who this message is from

          response = doCommand("MAIL FROM: " + sender);

          if (response.charAt(0) != '2') {
              print("At Mail from");
               throw new IOException(response);
          }


// Now tell the server who we want to send a message to

          response = doCommand("RCPT TO: " + recipient);

          if (response.charAt(0) != '2') {
              print("At rcpt to");
               throw new IOException(response);
          }

// Okay, now send the mail message

          response = doCommand("DATA");

// We expect a response beginning with '3' indicating that the server
// is ready for data.

          if (response.charAt(0) != '3') {
              print("At DATA");
               throw new IOException(response);
          }

// Send each line of the message

          for (int i=0; i < message.length; i++) {

             print((i+1)+"/"+message[i]);

// Check for a blank line
               if (message[i].length() == 0) {
                    outStream.writeBytes("\r\n");
                    continue;
               }

// If the line begins with a ".", put an extra "." in front of it.

               if (message[i].charAt(0) == '.') {
                    outStream.writeBytes("."+message[i]+"\r\n");
               } else {
                    outStream.writeBytes(message[i]+"\r\n");
               }
          }

// A "." on a line by itself ends a message.

          response = doCommand(".");

          if (response.charAt(0) != '2') {
              print("At send (.)");
               throw new IOException(response);
          }

          close();
     }

  void print(String msg) {

    System.out.println(msg);

  }
}



//File Base64.java

import java.io.*;
import java.util.Vector;
import java.util.StringTokenizer;
import java.util.Hashtable;
import java.net.*;



class Base64 {

  String zipfilename;
  Hashtable ht;

  Base64(String zfn) {

      zipfilename = zfn;
      
  }  


  public String[] encode() {

  String[] resultStringArray = null;

   try {

      File zipfile = new File(zipfilename);
      RandomAccessFile toGetSize = new RandomAccessFile(zipfilename,"r");
      byte[] uncoded = new byte[(int)toGetSize.length()];
      char[] coded;
      FileInputStream in = new FileInputStream(zipfile);

      in.read(uncoded,0,uncoded.length);
      
      coded = encode(uncoded);
      
      boolean ok = true;
      int buff=0, posInStringArray=0, sizeStringArray = coded.length/76;
      if (coded.length%76 != 0) sizeStringArray++;
      resultStringArray = new String[sizeStringArray];

      while (ok){
        
        char[] tmp = new char[76];
        for (int i=0;i<76 && buff<coded.length;i++,buff++)
          tmp[i] = coded[buff];
        String strTmp = new String(tmp);
        resultStringArray[posInStringArray] = strTmp;
        posInStringArray++;
        if (buff >= coded.length || posInStringArray >= sizeStringArray) ok = false;
        
      }

      

   } catch (Exception e) {

      System.out.println("Erro: "+e);
      
     }

  return resultStringArray;
 
  }
 
//////////////////////license & copyright header///////////////////////
//                                                                   //
//                Copyright (c) 1998 by Kevin Kelley                 //
//                                                                   //
// This program is free software; you can redistribute it and/or     //
// modify it under the terms of the GNU General Public License as    //
// published by the Free Software Foundation; either version 2 of    //
// the License, or (at your option) any later version.               //
//                                                                   //
// This program is distributed in the hope that it will be useful,   //
// but WITHOUT ANY WARRANTY; without even the implied warranty of    //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     //
// GNU General Public License for more details.                      //
//                                                                   //
// You should have received a copy of the GNU General Public License //
// along with this program in the file 'gpl.html'; if not, write to  //
// the Free Software Foundation, Inc., 59 Temple Place - Suite 330,  //
// Boston, MA 02111-1307, USA, or contact the author:                //
//                                                                   //
//                       Kevin Kelley  <kelley@iguana.ruralnet.net>  //
//                                                                   //
////////////////////end license & copyright header/////////////////////
//package starlight.util;

/**
*   Provides encoding of raw bytes to Base64-encoded characters, and
*  decoding of Base64 characters to raw bytes.
*
* @author Kevin Kelley (kelley@iguana.ruralnet.net)
* @version 1.0
* @date 06 August 1998
*/

/**
* returns an array of Base64-encoded characters to represent the
* passed data array.
*
* @param data the array of bytes to encode
* @return Base64-coded character array.
*/
static public char[] encode(byte[] data)
{
    char[] out = new char[((data.length + 2) / 3) * 4];

    //
    // 3 bytes encode to 4 chars.  Output is always an even
    // multiple of 4 characters.
    //
    for (int i=0, index=0; i<data.length; i+=3, index+=4) {
        boolean quad = false;
        boolean trip = false;

        int val = (0xFF & (int) data[i]);
        val <<= 8;
        if ((i+1) < data.length) {
            val |= (0xFF & (int) data[i+1]);
            trip = true;
        }
        val <<= 8;
        if ((i+2) < data.length) {
            val |= (0xFF & (int) data[i+2]);
            quad = true;
        }
        out[index+3] = alphabet[(quad? (val & 0x3F): 64)];
        val >>= 6;
        out[index+2] = alphabet[(trip? (val & 0x3F): 64)];
        val >>= 6;
        out[index+1] = alphabet[val & 0x3F];
        val >>= 6;
        out[index+0] = alphabet[val & 0x3F];
    }
    return out;
}

/**
* Returns an array of bytes which were encoded in the passed
* character array.
*
* @param data the array of Base64-encoded characters
* @return decoded data array
*/
static public byte[] decode(char[] data)
{
    int len = ((data.length + 3) / 4) * 3;
    if (data.length>0 && data[data.length-1] == '=') --len;
    if (data.length>1 && data[data.length-2] == '=') --len;
    byte[] out = new byte[len];

    int shift = 0;   // # of excess bits stored in accum
    int accum = 0;   // excess bits
    int index = 0;

    for (int ix=0; ix<data.length; ix++)
    {
        int value = codes[ data[ix] & 0xFF ];   // ignore high byte of char
        if ( value >= 0 ) {                     // skip over non-code
            accum <<= 6;            // bits shift up by 6 each time thru
            shift += 6;             // loop, with new bits being put in
            accum |= value;         // at the bottom.
            if ( shift >= 8 ) {     // whenever there are 8 or more shifted in,
                shift -= 8;         // write them out (from the top, leaving an
                out[index++] =      // excess at the bottom for next iteration.
                    (byte) ((accum >> shift) & 0xff);
    }   }   }
    if (index != out.length)
        throw new Error("miscalculated data length!");

    return out;
}

//
// code characters for values 0..63
//
static private char[] alphabet =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        .toCharArray();

//
// lookup table for converting Base64 characters to value in range 0..63
//
static private byte[] codes = new byte[256];
static {
    for (int i=0; i<256; i++) codes[i] = -1;
    for (int i = 'A'; i <= 'Z'; i++) codes[i] = (byte)(     i - 'A');
    for (int i = 'a'; i <= 'z'; i++) codes[i] = (byte)(26 + i - 'a');
    for (int i = '0'; i <= '9'; i++) codes[i] = (byte)(52 + i - '0');
    codes['+'] = 62;
    codes['/'] = 63;
}


}


0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6828239
This question was awarded, but never cleared due to the JSP-500 errors of that time.  It was "stuck" against userID -1 versus the intended expert whom you awarded.  This corrects the problem and the expert will now receive these points; points verified.

Please click on your Member Profile and select "View Question History" to navigate through any open or locked questions you may have to update and finalize them.  Or if you are an EE Pro user, click the link below to select open items for your Member ID using Power Search:
http://www.experts-exchange.com/jsp/qPowerSearch.jsp.

This is the Community Support link, if help is needed, along with the link to All Topics which reflects many TAs recently added.

http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
http://www.experts-exchange.com/jsp/zonesAll.jsp
 
Thank you,
Moondancer
Moderator @ Experts Exchange
0

Featured Post

Not sure which OpenStack Certification to get?

So you’ve realized you might want to get certified in OpenStack, but you’re not sure what the benefits might be or even which one you should take. You know there are several certification courses you can choose from, but how do you know which one is right for you?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question