Upload file and send email with attachment in ASP.NET MVC5 using Postal

So In previous post we came to know about Postal. yes it is easy.

We can send email in ASP.NET MVC easily.

So How about sending attachment using Postal Nuget package.

So I did create a sample project for uploading file and send email with that attachment using postal.

Indeed it is very easy.

Add Postal Your tool box.

  1. Create empty ASP.net MVC5 project
  2. Add Posta Package

nuget command

Then Package references are added and New folder is created as Email under the Views folder.

email folder

3. Added controller named HomeController and added simple view to enter email and upload file.

indexview

yes it is ugly. no need to worry. wanted make this work. no fancy works here.

indexviewui

4. Add smtp configurations to web.config

webconfig

I am using gmail smtp. fill user name and password. Postman will use this configurations to send emails.

5. Add coding to send email


[HttpPost]
public ActionResult Index(string email) {
if (!string.IsNullOrEmpty(email)) {
if (Request.Files.Count > 0) {

dynamic emailToSend = new Email("EmailWithAttachement");

byte[] data = new byte[0];
data = new byte[Request.Files[0].ContentLength];

var fileName = Request.Files[0].FileName;
var extension = Path.GetExtension(Request.Files[0].FileName);
Request.Files[0].InputStream.Read(data, 0, Request.Files[0].ContentLength);

using (var stream = new MemoryStream(data, true))
{
emailToSend.Attach(new Attachment(stream, fileName + extension));
emailToSend.To = email;
emailToSend.Send();
}
}
}

return View();
}

 

codes

Read uploaded file and convert it into byte array and attach it into email.

So finally we want to add view to be used by postal to send email.

Add view name “EmailWithAttachement” under email folder under Views folder.

emailview

edit view as below. you can edit view as you wish.

emailviewcode

finally run the project and enter email address and upload a file then email will be sent to provided email with attachment

actualemail

 

yes it is very simple.

Download source codeĀ here