Hi rani,
Using the below articles i have created the example.
Check this example. Now please take its reference and correct your code.
You need to install System.IO.Compression.ZipFile from nuget manager.
Namespaces
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(List<IFormFile> postedFiles)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
List<string> uploadedFiles = new List<string>();
foreach (IFormFile postedFile in postedFiles)
{
string fileName = Path.GetFileName(postedFile.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
postedFile.CopyTo(stream);
uploadedFiles.Add(Path.Combine(path, fileName));
}
}
using (MemoryStream ms = new MemoryStream())
{
// Creates the zip.
using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
foreach (string uploadedFile in uploadedFiles)
{
FileInfo file = new FileInfo(uploadedFile);
// Creates empty file and names it inside of zip.
ZipArchiveEntry zipItem = archive.CreateEntry(file.Name + file.Extension);
// Add file to zipItem.
using (MemoryStream msFile = new MemoryStream(System.IO.File.ReadAllBytes(uploadedFile)))
{
using (Stream stream = zipItem.Open())
{
msFile.CopyTo(stream);
}
}
}
}
// Send Email with zip as attachment.
using (MailMessage mm = new MailMessage("sender@gmail.com", "recipient@gmail.com"))
{
mm.Subject = "Documents";
mm.Body = "Attachment: Customer's documents";
mm.Attachments.Add(new Attachment(new MemoryStream(ms.ToArray()), "Document.zip"));
mm.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential
{
UserName = "sender@gmail.com",
Password = "password"
};
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(mm);
}
}
// Delete uploaded files.
Directory.Delete(path, true);
}
return View();
}
}
View
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<span>Select File:</span>
<input type="file" name="postedFiles" multiple />
<input type="submit" value="Upload" />
</form>
</body>
</html>