Hi,
You may want to have a look at
NMS Formmail.
If you really wanted to roll your own you may get some ideas from it.
If its features and config match your requirements you may just want to use it.
I have used it in a previous job at an ISP when the existing mail gateway sciprt given to users was found to have a rather serious flaw in it.
This topic has been touched on before, you may want to do a
Super Search.
Hope this helps.
Martin