1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ApplicationMail.Models;
using System.IO;
using System.Net.Mail;
using System.Net;
namespace ApplicationMail.Controllers{
public class MailController : Controller{
public ActionResult Index(){
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitCV(HttpPostedFileBase file){
if (file == null){
ModelState.AddModelError("CustomError", "Please select your file");
return View();
}
if (!(file.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
file.ContentType == "application/pdf")){
ModelState.AddModelError("CustomError", "Only .docx and .pdf file allowed");
return View();
}
if (ModelState.IsValid){
try{
string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
file.SaveAs(Path.Combine(Server.MapPath("~/UploadedCV"), fileName));
ViewBag.Message = "Successfully Done";
}
catch (Exception ex){
ViewBag.Message = "Error! Please try again";
return View();
}
}
return View();
}
[HttpPost]
public ActionResult Index(ApplicationMail.Models.Mail objModelMail, String From, String password, HttpPostedFileBase file){
if (ModelState.IsValid){
using (MailMessage mail = new MailMessage(From, objModelMail.To)){
mail.Subject = objModelMail.Subject;
mail.Body = objModelMail.Body;
if (file != null){
string fileName = Path.GetFileName(file.FileName);
mail.Attachments.Add(new Attachment(file.InputStream, fileName));
}
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(From, password);
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
ViewBag.Message = "Sent";
return View("Index", objModelMail);
}
}
else{
return View();
}
}
}
} |
Partager