Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
- {
- if (ModelState.IsValid)
- {
- List<string> paths = new List<string>();
- foreach (var file in files)
- {
- if (file.ContentLength > 0)
- {
- var fileName = Path.GetFileName(file.FileName);
- var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
- file.SaveAs(path);
- paths.Add(path);
- }
- }
- var message = new MailMessage();
- foreach (var path in paths)
- {
- var fileInfo = new FileInfo(path);
- var memoryStream = new MemoryStream();
- using (var stream = fileInfo.OpenRead())
- {
- stream.CopyTo(memoryStream);
- }
- memoryStream.Position = 0;
- string fileName = fileInfo.Name;
- message.Attachments.Add(new Attachment(memoryStream, fileName));
- }
- //Rest of business logic here
- string EncodedResponse = Request.Form["g-Recaptcha-Response"];
- bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
- if (IsCaptchaValid)
- {
- var body = "<p>Email From: {0} ({1})</p><p>Subject: {2} </p><p>Message:</p><p>{3}</p>";
- message.To.Add(new MailAddress("***@gmail.com")); // replace with valid value
- message.From = new MailAddress("***@ymailcom"); // replace with valid value
- message.Subject = "Your email subject";
- message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
- message.IsBodyHtml = true;
- using (var smtp = new SmtpClient())
- {
- var credential = new NetworkCredential
- {
- UserName = "***@gmail.com", // replace with valid value
- Password = "***" // replace with valid value
- };
- smtp.Credentials = credential;
- smtp.Host = "smtp.gmail.com";
- smtp.Port = 587;
- smtp.EnableSsl = true;
- await smtp.SendMailAsync(message);
- ViewBag.Message = "Your message has been sent!";
- ModelState.Clear();
- return View("Index");
- }
- }
- else
- {
- TempData["recaptcha"] = "Please verify that you are not a robot!";
- }
- }return View(model);
- }
- public class ReCaptcha
- {
- private string m_Success;
- [JsonProperty("success")]
- public string Success
- {
- get { return m_Success; }
- set { m_Success = value;}
- }
- private List<string> m_ErrorCodes;
- [JsonProperty("error-codes")]
- public List<string> ErrorCodes
- {
- get { return m_ErrorCodes; }
- set { m_ErrorCodes = value; }
- }
- public static string Validate(string EncodedResponse)
- {
- var client = new System.Net.WebClient();
- string PrivateKey = "***";
- var reply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));
- var captchaResponse = JsonConvert.DeserializeObject<ReCaptcha>(reply);
- return captchaResponse.Success;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement