See the following code:
import java.io.*;
import java.util.*;
import java.text.*;
import javax.mail.*;
import javax.servlet.*;
import javax.activation.*;
import javax.servlet.http.*;
import javax.mail.internet.*;
public class WebSMTP extends HttpServlet
{
protected static final String composeForm =
"WebSMTP" +
"
"ENCTYPE="multipart/form-data">" +
"
From: " +
"
To: " +
"
Cc: " +
"
Subject: " +
"
" +
"
" +
"
",
okForm =
"
WebSMTP" +
"
Mail sent successfully" +
"
Write another" +
"";
protected void printForm(String form, HttpServletRequest request,
HttpServletResponse response)
throws IOException
{
PrintWriter writer = response.getWriter();
form = MessageFormat.format(form,
new Object[] { request.getRequestURI() });
writer.print(form);
writer.flush();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
printForm(composeForm,request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
try
{
if(request.getContentType().startsWith("multipart/form-data"))
doUpload(request,response);
else
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
catch(Exception e)
{
PrintWriter writer = response.getWriter();
writer.println("
Oops!");
e.printStackTrace(writer);
writer.println("
");
writer.flush();
}
}
protected void doSendMessage(HttpServletRequest request, HttpServletResponse response,
Dictionary fields)
throws IOException, MessagingException
{
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom( new InternetAddress((String)fields.get("from")));
InternetAddress[] tos = InternetAddress.parse((String)fields.get("to"));
msg.setRecipients(Message.RecipientType.TO,tos);
if(fields.get("cc") != null)
{
InternetAddress[] ccs = InternetAddress.parse((String)fields.get("cc"));
msg.setRecipients(Message.RecipientType.CC,ccs);
}
msg.setSubject((String)fields.get("subject"));
msg.setSentDate(new Date());
if(null == fields.get("attachment"))
msg.setText((String)fields.get("body"));
else
{
BodyPart body = new MimeBodyPart(), attachment = (BodyPart)fields.get("attachment");
body.setText((String)fields.get("body"));
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachment);
msg.setContent(multipart);
}
Transport.send(msg);
printForm(okForm,request,response);
}
public void doUpload(HttpServletRequest request, HttpServletResponse response)
throws IOException, MessagingException
{
String name = null, value = null, filename = null, contentType = null;
String boundary = request.getHeader("Content-Type");
int pos = boundary.indexOf('=');
boundary = boundary.substring(pos + 1);
boundary = "--" + boundary;
ServletInputStream in = request.getInputStream();
byte[] bytes = new byte[512];
int state = 0;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Dictionary fields = new Hashtable();
int i = in.readLine(bytes,0,512);
while(-1 != i)
{
String st = new String(bytes,0,i);
if(st.startsWith(boundary))
{
state = 0;
if(name != null)
{
if(value != null)
// -2 to remove CR/LF
fields.put(name, value.substring(0, value.length() - 2));
else if(buffer.size() > 2)
{
InternetHeaders headers = new InternetHeaders();
MimeBodyPart bodyPart = new MimeBodyPart();
DataSource ds = new ByteArrayDataSource( buffer.toByteArray(),
contentType,filename);
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setDisposition("attachment; filename="" +
filename + """);
bodyPart.setFileName(filename);
fields.put(name,bodyPart);
}
name = null;
value = null;
filename = null;
contentType = null;
buffer = new ByteArrayOutputStream();
}
}
else if(st.startsWith("Content-Disposition: form-data") && state == 0)
{
StringTokenizer tokenizer = new StringTokenizer(st,";="");
while(tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
if(token.startsWith(" name"))
{
name = tokenizer.nextToken();
state = 2;
}
else if(token.startsWith(" filename"))
{
filename = tokenizer.nextToken();
StringTokenizer ftokenizer = new StringTokenizer(filename,"\/:");
filename = ftokenizer.nextToken();
while(ftokenizer.hasMoreTokens())
filename = ftokenizer.nextToken();
state = 1;
break;
}
}
}
else if(st.startsWith("Content-Type") && state == 1)
{
pos = st.indexOf(":");
// + 2 to remove the space
// - 2 to remove CR/LF
contentType = st.substring(pos + 2,st.length() - 2);
}
else if(st.equals("
") && state == 1)
state = 3;
else if(st.equals("
") && state == 2)
state = 4;
else if(state == 4)
value = value == null ? st : value + st;
else if(state == 3)
buffer.write(bytes,0,i);
i = in.readLine(bytes,0,512);
}
doSendMessage(request,response,fields);
}
class ByteArrayDataSource implements DataSource
{
byte[] bytes;
String contentType, name;
ByteArrayDataSource(byte[] bytes, String contentType, String name)
{
this.bytes = bytes;
if(contentType == null)
this.contentType = "application/octet-stream";
else
this.contentType = contentType;
this.name = name;
}
public String getContentType()
{
return contentType;
}
public InputStream getInputStream()
{
// remove the final CR/LF
return new ByteArrayInputStream(bytes,0,bytes.length - 2);
}
public String getName()
{
return name;
}
public OutputStream getOutputStream() throws IOException
{
throw new FileNotFoundException();
}
}
}