Hi,
How to save and send email at the same time after submit form?
I tried to edit the code from previous sample but it didn't work. There is no error display just the email is not send.
So here is my controller part.
[HttpPost]
public ActionResult AddDetail(MaterialDetail Imodel)
{
string id2;
try
{
string id = db.Requesters.Max(x => x.Requester_id);
if (id == null)
{
id2 = "FY21_001";
}
else
{
string NewID = id.Split('_')[1];
id2 = "FY21_" + (int.Parse(NewID) + 1).ToString().PadLeft(3, '0');
TempData["id2"] = id2;
}
var EmailBody = "<p>Hi Team,</p>" +
"Please take note on the below material requested. <br/><br/>";
///save data into Requester table
Requester model = new Requester();
model.Requester_id = id2;
model.req_name = Imodel.req_name;
model.address = Imodel.address;
model.phone = Imodel.phone;
model.req_date = DateTime.Now;
model.status = "New";
model.aprrove = false;
model.remark = Imodel.remark;
EmailBody += "Requester : " + model.req_name + "<br/>";
EmailBody += "Address : " + model.address + "<br/>";
EmailBody += "phone : " + model.phone + "<br/>";
EmailBody += "Request Date : " + model.req_date + "<br/><br/>";
EmailBody += "Remark (if any) : " + model.remark + "<br/><br/>";
string subject = "Material Request - " + model.req_date;
db.Requesters.Add(model);
///save data into Material_Item table
for (int i = 0; i < Imodel.MaterialDetails.Count; i++)
{
Material_Item item = new Material_Item();
item.Requester_id = id2;
item.req_quantity = Imodel.MaterialDetails[i].Quantity;
item.req_material = Imodel.MaterialDetails[i].MaterialName;
EmailBody += "<tr>";
EmailBody += "<td>" + item.req_material + "</td>";
EmailBody += "<td>" + item.req_quantity + "</td>";
EmailBody += "</tr>";
db.Material_Item.Add(item);
EmailBody += "</table>";
EmailBody += " Thank you.</ p > ";
string EmailFrom = "Customer_order@gmail.com";
EmailService(EmailFrom, subject, EmailBody);
/////minus quantity from iventory(MaterialList table)
MaterialList list = db.MaterialLists.Where(y => y.Material == item.req_material).FirstOrDefault();
if (list != null)
{
list.Mat_Quantity = list.Mat_Quantity - item.req_quantity;
}
db.SaveChanges();
}
}
catch (Exception)
{
}
return RedirectToAction("FormRequest", "Home");
}
[NonAction]
public void EmailService(string EmailFrom, string subject, string body)
{
MailMessage message = new MailMessage();
var query = db.admin_detail.ToList();
foreach (var item in query)
{
message.To.Add(item.email);
}
message.From = new MailAddress(EmailFrom, "Customer Order");
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Send(message);
}