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;
  
 import java.util.Date;
 import java.util.List;
 
Deliver an email message via an SMTP server. Note this feature is custom written because this facility does not always work out of the box on all systems. Based upon but not fully tested against RFC 821 and RFC 2822. Example usage:

 Mail m=new Mail("smtp.example.com");

 if(m.testConnection() == 0) {
     System.out.println("Connection to mailserver available");
 } else {
     System.out.println("Problem with specified mailserver: "+m.getError());
 }

 m.enableAuthentication("jacob@example.com","password");
  int result = m.sendMail("bob@example.com","jane@example.com","My subject","content2");
 if(result>0) {
     System.err.println(m.getError());
 }

 result=m.sendMail("xiongmao@example.com","gou@example.com","Another subject","content2");
 if(result>0) {
     System.err.println(m.getError());
 }

 result=m.sendMails("bob@example.com","person1@example.com,person2@example.com","test1","content");
 if(result>0) {
     System.err.println(m.getError());
 }
 
 
 public class Mail {
 
 	private String host = null;
 	private int port = 25;
 	private String error = "";
 	private static Random generator = new Random();
 	private int timeout = 10000;
 
 	public Mail(String hostint port) {
 		this. = host;
 		this. = port;
 	}
 
 	public Mail(String host) {
 		this.=host;
 	}
 
 	String authUsername = null;
 	String authPassword = null;
 	boolean authEnabled = false;

Attempt to authenticate to the mail server, primarily used to enable relaying of email where required.

Parameters:
username Provide account username
password Specify account password
 
 	public void enableAuthentication(String usernameString password) {
 		 = username;
 		 = password;
 		 = true;
 	}

Disable attempting to authenticate with mail server.
	public void disableAuthentication() {
		 = null;
		 = null;
		 = false;
	}

Used to retrive the error message related generated due to failure of sendMail() function.

Returns:
Text string containing english description of problem.
	public String getError() {
		String e2 = ;
		 = "";
		return e2;
	}

Specify maximum length of time in milliseconds to wait for an SMTP server to respond. Default is ten seconds.

Parameters:
timeout Maximum wait time in milliseconds
	public void setTimeout(int timeout) {
		this. = timeout;
	}

The maximum length of time to wait for an SMTP server to respond

Returns:
Maximum wait time in milliseconds
	public int getTimeout() {
		return ;
	}

Send and email to multiple addresses in plain text format, no html or mime encoding. Specify multiple addresses in the to field separated by a comma.

Parameters:
from Sender email address.
to Destination email addresses separated by a comma.
subject Subject of email message.
textContent content of email message to be sent.
Returns:
0 if successful, otherwise error number returned.
	public int sendMails(String fromString toString subjectString textContent) {
		int retval=0;
		String[] a=to.split(" *, *");
		for(int i = 0; i < a.lengthi++) {
			int status = sendMail(froma[i], subjecttextContent, (List<String>)null"");
			if(status > 0) {
				 = "Problem occured while sending one of the messages.";
				retval = 1;
			}
		}
		return retval;
	}
	public int sendHtmlMail(String fromString toString subjectString content) {
		List<Stringheaders=new ArrayList<String>();
		headers.add("Content-type: text/html; charset=UTF-8");
		headers.add("Mime-Version: 1.0");
		return sendMail(fromtosubjectcontentheaders"");
	}

Parameters:
from
to
subject
html HTML version of the email
text Text alternative version of the email
Returns:
0 if successful, otherwise error number returned.
	public int sendHtmlMail(String fromString toString subjectString htmlString text) {
		return sendMail(fromtosubjecthtmlnulltext);
	}
	public int sendHtmlMail(String fromString toString subjectString contentString altList<Stringheaders) {
		return sendMail(fromtosubjectcontentheadersalt);
	}

Send a message in plain text format, no html or mime encoding

Parameters:
from Sender email address.
to Destination email address.
subject Subject of email message.
content content of email message to be sent.
Returns:
0 if successful, otherwise error number returned.
	public int sendMail(String fromString toString subjectString content) {
		return sendMail(fromtosubjectcontent, (List<String>)null"");
	}

Send a message in plain text format, no html or mime encoding

Parameters:
from Sender email address.
to Destination email address.
subject Subject of email message.
content content of email message to be sent.
Returns:
0 if successful, otherwise error number returned.
	public int sendMail(String fromString toString subjectString contentList<Stringheaders) {
		return sendMail(fromtosubjectcontentheaders"");
	}

Send a message in plain text format, no html or mime encoding

Parameters:
from Sender email address.
to Destination email address.
subject Subject of email message.
html content of email message to be sent.
headers Extra header lines to insert, this may be null.
Returns:
0 if successful, otherwise error number returned.
	public int sendMail(String fromString toString subjectString htmlList<StringheadersString text) {
		Socket socket = null;
		String response = null;
		String datestamp = "";
		Format dformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
		datestamp = dformat.format(new Date());
		Pattern p = Pattern.compile("[\"']*([^\"'<]*)[\"']* *<([^>]*)>");
		String fromEmail = from;
		String fromName = "";
		if(from.indexOf('<') > 0) {
			Matcher m = p.matcher(from);
			if(m.matches()) {
				fromName = m.group(1);
				fromEmail = m.group(2);
			}
		}
		String toEmail = to;
		String toName = "";
		if(to.indexOf('<') > 0) {
			Matcher m = p.matcher(to);
			if(m.matches()) {
				toName = m.group(1);
				toEmail = m.group(2);
			}
		}
		if(!etest.isValid(fromEmail)) {
			 = etest.getError();
			return 1;
		}
		if(!etest.isValid(toEmail)) {
			 = etest.getError();
			return 1;
		}
		try {
			socket = new Socket();
			socket.connect(sockaddr);
catch(SocketTimeoutException e) {
			 = "Timeout while connecting to mail server";
			if(socket != null) { try { socket.close(); } catch(IOException f) {} }
			return 2;
catch(IOException e) {
			 = "Unable to connect to mail server";
			if(socket != null) { try { socket.close(); } catch(IOException f) {} }
			return 1;
		}
		try {
			InetAddress lina = InetAddress.getLocalHost();
			PrintStream ps = new PrintStream(socket.getOutputStream());
			BufferedReader dis = new BufferedReader(dd);
			response=dis.readLine();
			if(response.indexOf("220 ") != 0) {
				 = "Mail did not respond like a mail server";
				return 1;
			}
			ps.println("HELO " + lina.toString()); ps.flush();
			response = dis.readLine();
			if(response.indexOf("250 ") != 0) {
				 = response;
				return 1;
			}
				ps.println("AUTH LOGIN");
				ps.flush();
				response = dis.readLine();
				if(response.indexOf("334 ") != 0) {
					 = response;
					return 1;
				}
				ps.println(Base64Encode.encode());
				ps.flush();
				response=dis.readLine();
				if(response.indexOf("334 ") != 0) {
					 = response;
					return 1;
				}
				ps.println(Base64Encode.encode());
				ps.flush();
				response = dis.readLine();
				if(response.indexOf("235 ") != 0) {
					 = response;
					return 1;
				}
			}
			ps.println("MAIL FROM:" + fromEmail);
			ps.flush();
			response = dis.readLine();
			if(response.indexOf("250 ") != 0) {
				=response;
				return 1;
			}
			ps.println("RCPT TO:" + toEmail);
			ps.flush();
			response=dis.readLine();
			if(response.indexOf("250 ") != 0) {
				 = response;
				return 1;
			}
			ps.println("DATA");
			response = dis.readLine();
			if(response.indexOf("354 ") != 0) {
				 = response;
				return 1;
			}
			ps.println("Date: " + datestamp);
			if(fromName.length() > 0) {
				ps.println("From: \""+fromName+"\" <"+fromEmail+">");
else {
				ps.println("From: "+fromEmail);
			}
			ps.println("Subject: "+subject);
			if(toName.length() > 0) {
				ps.println("To: \"" + toName + "\" <" + toEmail + ">");
else {
				ps.println("To: " + toEmail);
			}
			String messageId = null;
			if(headers != null) {
				for(String header : headers) {
					ps.println(header);
					if(header.toLowerCase().startsWith("message-id:")) {
						messageId = header;
					}
				}
			}
			if(messageId == null) {
				ps.println("Message-ID: <"+(new base.uuid.UUID().toString().toUpperCase())+"@"+lina.toString()+">");
			}
			if(html != null && html.length() > 0) {
				Encoding quotedPrintable = new QuotedPrintableEncoding();
				html = quotedPrintable.encode(html);
				Encoding plainText = new PlainTextEncoding();
				text = plainText.encode(text);
				String boundary = String.valueOf(Math.abs(.nextLong()));
				ps.println("Content-type: multipart/alternative; charset=UTF-8;  boundary="+boundary);
				ps.println("Mime-Version: 1.0");
				ps.println("");
				ps.println("--"+boundary);
				ps.println("Content-Type: text/plain; charset=utf-8; format=flowed");
				ps.println("Content-Transfer-Encoding: 8bit");
				ps.println("Content-Disposition: inline");
				ps.println("");
				ps.println(text);
				ps.println("");
				ps.println("--"+boundary);
				ps.println("Content-Type: text/html; charset=utf-8");
				ps.println("Content-Transfer-Encoding: quoted-printable");
				ps.println("Content-Disposition: inline");
				ps.println("");
				ps.println(html);
				ps.println("");
				ps.println("--"+boundary+"--");
else {
				ps.println("");
				Encoding plainText = new PlainTextEncoding();
				text = plainText.encode(text);
				ps.println(text);
				ps.println("");
			}
			ps.println("."); ps.flush();
			response=dis.readLine();
			if(response == null) {
				 = "Error reading data from server. ";
				return 1;
			}
			if(response.indexOf("250 ") != 0) {
				 = response;
				return 1;
			}
			ps.println("QUIT"); ps.flush();
			response=dis.readLine();
			if(response == null) {
				 = "Error reading data from server. ";
				return 1;
			}
			if(response.indexOf("221 ") != 0) {
				 = response;
				return 1;
			}
catch(SocketTimeoutException e) {
			 = "Timeout while waiting for response from to mail server";
			return 4;
catch (Exception ex) {
			 = "Problem communicating with mail server. " + StringHelper.exceptionToString(ex"\n  ");
			return 2;
finally {
			if(socket != null) { try { socket.close(); } catch(IOException f) {} }
		}
		return 0;
	}

Used to test connection and communication with the specified mail server. Will report if a connection can not be established with the mail server or if the mailserver does not reply with content a mail server should reply with, or finally if there are network difficulties at the time of the test.

Returns:
0 if successful, >0 if not successful. Use getError() to read the problem.
	public int testConnection() {
		Socket socket = null;
		String response = null;
		try {
			socket = new Socket();
			socket.connect(sockaddr);
catch(SocketTimeoutException e) {
			 = "Timeout while connecting to mail server";
			if(socket != null) { try { socket.close(); } catch(IOException f) {} }
			return 3;
catch(IOException e) {
			 = "Unable to connect to mail server";
			if(socket != null) { try { socket.close(); } catch(IOException f) {} }
			return 1;
		}
		try {
			PrintStream ps = new PrintStream(socket.getOutputStream());
			BufferedReader dis = new BufferedReader(dd);
			response = dis.readLine();
			if(response.indexOf("220 ") != 0) {
				="Mail did not respond like a mail server";
				return 1;
			}
			ps.println("QUIT");
			ps.flush();
			response = dis.readLine();
			if(response.indexOf("221 ") != 0) {
				 = response;
				return 1;
			}
catch(SocketTimeoutException e) {
			 = "Timeout while waiting for response from to mail server";
			try { socket.close(); } catch(IOException f) {}
			return 4;
catch (Exception e) {
			 = "Problem communicating with mail server. " + e.getMessage();
			try { socket.close(); } catch(IOException f) {}
			return 2;
		}
		try { socket.close(); } catch(IOException e) {}
		return 0;
	}
New to GrepCode? Check out our FAQ X