I need to make form with a textarea and an image upload field. When somebody submit it I want it to send email (with text from textarea) with attachements (from input file upload field) to me.
My simple form looks like that:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
@Html.TextArea("Question");
<input type="file"/>
<input type="submit" value="Send" />
</fieldset>
}
I found PHP scripts that are doing something like that, but how could I do it in ASP.NET MVC (could be with JavaScript)?
Here's an example using gmail's SMTP but if you have your own SMTP server you could easily adapt the code.
As always I would start with a view model:
then a controller:
and finally a view:
A further improvement to this code would be to externalize the actual sending of the mail into a repository implementing some interface and using DI in order to weaken the coupling between the controller logic and the mail sending logic.
Note that you can also configure your SMTP settings in web.config:
and then simply:
MailMessage class in .NET should be able to handle that for you:
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments.aspx
Or are you looking for something more specific to your actual code? (e.g. how to read the file and add it to the attachment)?
In addition to Daren's answer, you don't have to hardcode the input and label for your file upload in your view. Just slap this in there :)