Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Creative commons Attribution-NonCommercial license. http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
  
  package base.email;
  
 
Provides basic access to an IMAP account, without requring learning a huge chunky library. Example usage:
 ImapReader i = new ImapReader();
 i.setHostname("mailserver.com");
 i.setUsername("user@mailserver.com");
 i.setPassword("password");
 try {
  i.connect();
  int count = i.readMailbox("INBOX");
  System.out.println("Found "+count+" emails.");
  for(int x = 1; x <= count; x++) {
    i.readMail(x);
  }
  i.logout();
 } catch(IOException e) {
  System.out.println("Problem accessing server. "+e);
 }
 
 
 public class ImapReader {
 	static Socket imap = null;
 	static OutputStreamWriter outStream = null;
 	static InputStream inStream = null;
 	static BufferedReader reader = null;

Default to insecure port 143, use port 993 for SSL
 
 	private int port = 143;
 
 	private String host = "";
 	private String username = "";
 	private String password = "";
 	private int command = 1;
 	private boolean ssh = false;

Specify the host name to connect to.
 
 	public void setHostname(String h) {
 		 = h;
 	}

Specify the user name to be used for this transaction.

Parameters:
u Username to provide to IMAP server.
 
 	public void setUsername(String username) {
 		if(username == null) {
 			username = "";
 		}
 		this.=username;
 	}

Specify the password to be used with this transaction.

Parameters:
p The password to use for this connection.
 
 	public void setPassword(String password) {
 		if(password == null) {
 			password = "";
 		}
 		this. = password;
 	}

Initiate connection to the server
 
 	public int connect() throws IOException {
 		SSLContext sc = null;
 		String line = null;
 		Random r = new Random();
 		 = Math.abs(r.nextInt()%1000000);
 
		try {
			if() {
				/*
				 * Create a trust manager that does not validate certificate chains
				 */
				TrustManager[] trustAllCerts=new TrustManager[]{
							getAcceptedIssuers() { return null; }
						public void checkClientTrusted(
							authType) { }
						public void checkServerTrusted(
							authType) { }
					}
				};
				// Install the all-trusting trust manager
				try {
					sc = SSLContext.getInstance("SSL");
					sc.init(nulltrustAllCertsnew java.security.SecureRandom());
catch (Exception e) {
				}
				// connect with the IMAP server
				SocketFactory socketFactory = sc.getSocketFactory();
				 = socketFactory.createSocket();
else {
				 = new Socket(, 143);
			}
			line = readLine();
			if(!line.substring(0, 4).equalsIgnoreCase("* OK")) {
				return 2;
			}
			write("LOGIN "++" "+);
			line = readLine();
			if(!line.substring(0, 5).equalsIgnoreCase("J1 OK")) {
				return 4;
			}
catch(UnknownHostException e) {
			throw new IOException("Unable to resolve hostname."e);
		}
		return 0;
	}

Marks a message as deleted/ready for deletion. @param id Id of the mail as provided by the readMail function.
	public void deleteMail(int idthrows IOException {
		write("store "+id+" +FLAGS (\\Deleted)");
		String line = readLine();
		while(line.charAt(0) == '*') {
			line = readLine();
		}
	}

Flushes all email messages that are marked for deletion.
	public void emptyTrash() throws IOException {
		write("expunge");
		String line = readLine();
		while(line.charAt(0) == '*') {
			line=readLine();
		}
	}
	private static final Pattern END_CHECK = Pattern.compile("J(\\d+) OK.*");

Read contents of a particular email. May only be called after first using the readMailbox function to select which mail folder we which to read.

Parameters:
id of email
Returns:
Contents of email.
	public EmailMessage readMail(int idthrows IOException {
		StringBuffer content=new StringBuffer();
		write("fetch "+id+" body[header]");
		String line = readLine();
		while(true) {
			if(m.matches()) {
				break;
			}
			if(line.length() > 0 && (line.charAt(0) == ' ' || line.charAt(0) == '\t')) {
				content.append(line);
else {
				content.append("\n");
				content.append(line);
			}
			line=readLine();
		}
		e.setHeaders(content.toString());
		content = new StringBuffer();
		write("fetch "+id+" body[text]");
		line=readLine(); //Skip first line, its just the command response
		line=readLine();
		while(true) {
			if(m.matches()) {
				break;
			}
			content.append(line);
			content.append("\n");
			line=readLine();
		}
		String data = content.toString();
		data=data.substring(0, data.lastIndexOf(')'));
		e.setBody(data);
		return e;
	}

Download the exact content of the full email message.

Parameters:
id of email
Returns:
String containing the entire message content
	public String downloadMessage(int idthrows IOException {
		StringBuffer content = new StringBuffer();
		String line;
		write("fetch "+id+" body[header]");
		line = readLine(); //TODO: We currently ignore response line!
		line = readLine();
		while(true) {
			if(m.matches()) {
				break;
			}
			content.append(line);
			content.append("\n");
			line = readLine();
		}
		content.append("\n");
		String data = content.toString();
		data = data.substring(0, data.lastIndexOf(')'));
		content = new StringBuffer();
		write("fetch "+id+" body[text]");
		line = readLine(); //TODO: We currently ignore response line!
		line = readLine();
		while(true) {
			if(m.matches()) {
				break;
			}
			content.append(line);
			content.append("\n");
			line = readLine();
		}
		data = data+content.toString();
		data = data.substring(0, data.lastIndexOf(')'));
		return data;
	}
	private static final Pattern EXIST_CHECK = Pattern.compile(".*\\* (\\d+) EXIST.*");

Select a particular mail box for reading. Once selected, use the readMail() command to read the messages in this folder.

Returns:
Total number of email's in this mail box.
	public int readMailbox(String emailthrows IOException {
		write("select "+email);
		String line = readLine();
		int count = 0;
		//write("fetch "+1+" body[text]");
		//line=readLine();
		while(line.charAt(0) == '*') {
			if(m.matches()) {
				count = Integer.parseInt(m.group(1));
			}
			line=readLine();
		}
		return count;
	}

Once all actions are completed, logout is called to disconnect from the server.
	public void logout() {
		try {
			write("logout");
catch(IOException e) {
		}
	}

Cleanup all connections and data when complete
	private void disconnect() {
		try {
			if( != null) { .close();  = null; }
			if( != null) { .close();  = null; }
			if( != null) { .close();  = null; }
			if( != null) { .close();  = null; }
catch(IOException e) { }
	}
	private String lastCommand = "";

Sent a command to the server
	private void write(String cmdthrows IOException {
		 = cmd;
		try {
			.write("J"++" "+cmd+"\n");
catch(IOException e) {
			throw e;
		}
	}

Read response from the server
	private String readLine() throws IOException{
		try {
			String line = .readLine();
			if(line.indexOf("J"++" BAD") == 0) {
				throw new IOException("Imap server responded 'BAD' to "+);
			}
			if(line.indexOf("J"++" NO") == 0) {
				throw new IOException("Imap server responded 'NO' to "+);
			}
			return line;
catch(IOException e) {
			throw e;
		}
	}
New to GrepCode? Check out our FAQ X