package imap; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; // Using the IMAP protocol // This servlet will take in the current mailbox, email, and // tomailbox parameter... copy the current email to the chosen // mailbox, and bring you back to email viewing mode public class ImapCopyBox extends HttpServlet { // Defining resulting object out from request req and response res public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); ServletOutputStream out=res.getOutputStream(); try { // Retrieve login information from preset cookie Cookie[] cookie=new Cookie[3]; String[] login=new String[3]; cookie=req.getCookies(); String username="0", password="0", hostname="0"; for(int i=0; i<=2; i++) { login[i]=cookie[i].getName(); if (login[i].equals("username")) username=cookie[i].getValue(); else if (login[i].equals("password")) password=cookie[i].getValue(); else if (login[i].equals("hostname")) hostname=cookie[i].getValue(); } // Retrieve parameter information String email=req.getParameter("email"); String mailbox=req.getParameter("mailbox"); String tomailbox=req.getParameter("tomailbox"); // Creating a socket to the desired hostname's IMAP port Socket socket=new Socket(hostname, 143); PrintStream write_socket=new PrintStream(socket.getOutputStream()); DataInputStream read_socket=new DataInputStream(socket.getInputStream()); // Make sure target IMAP port is ready String imap_res=read_socket.readLine(); if (! imap_res.startsWith("* OK")) throw new ServletException("IMAP Server was not reachable this time"); int command=1; // Make sure a correct username and/or password is provided write_socket.println(command+" login "+username+" "+password); imap_res=read_socket.readLine(); if (! imap_res.startsWith(command+" OK")) throw new ServletException("Invalid Username and/or Password"); // Select inbox command++; write_socket.println(command+" select "+mailbox); imap_res=read_socket.readLine(); if (imap_res.startsWith(command+" BAD") || imap_res.startsWith(command+" NO") ) throw new ServletException("Invalid Mailbox"); while (! imap_res.startsWith(command+" OK")) imap_res=read_socket.readLine(); command++; write_socket.println(command+" copy "+email+" "+tomailbox); imap_res=read_socket.readLine(); if (imap_res.startsWith(command+" BAD") || imap_res.startsWith(command+" NO") ) throw new ServletException("Invalid ToMailbox"+email+" "+mailbox+" "+tomailbox); while (! imap_res.startsWith(command+" OK")) imap_res=read_socket.readLine(); command++; // Retrieve the headers for all the messages and print out to html page write_socket.println(command+" fetch "+email+" (body[header.fields (from date subject)] body[text])"); read_socket.readLine(); imap_res=read_socket.readLine(); if (imap_res.startsWith(command+" BAD") || imap_res.startsWith(command+" NO") ) throw new ServletException("Invalid Email message"); out.println("