简体   繁体   中英

Send email and save it in database (ASP.NET MVC)

I've been working on a website using ASP.NET MVC, in this website you can directly send an email to a specific email address. It's working properly, but the information being sent in the email (like Name, Email Address, ect.) don't have a database. So I tried adding a database for it, but somehow it's not working and I keep having some errors. I'm just new with this kind of stuff so I'm not sure if it's possible to send the email and at the same time save it to a database. I know there's something wrong with what I'm doing, so someone please help me. Thank you.

Here's my Controller for the sending of email:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {
            RegisterRepository regRepo = new RegisterRepository();

            if (regRepo.Register(model))
            {
                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><b>Email From:</b> {0} ({1})</p><p><b>Message:<b></p><p>{2}</p>";
                    message.To.Add(new MailAddress("***@gmail.com"));  // replace with valid value 
                    message.From = new MailAddress("***@ymailcom");  // replace with valid value
                    message.Subject = "YesDubai.org (REGISTRATION)";
                    message.Body = string.Format(body, model.Talent_Name, model.Talent_Email, model.Talent_SelfPromotion);
                    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;
                        smtp.SendCompleted += (s, e) =>
                        {
                            //delete attached files
                            foreach (var path in paths)
                                System.IO.File.Delete(path);
                        };
                        await smtp.SendMailAsync(message);
                        ViewBag.Message = "Your message has been sent!";

                        ModelState.Clear();
                        return View("Register");
                    }
                }
                else
                {
                    TempData["recaptcha"] = "Please verify that you are not a robot!";
                }

            } return View(model);

        }
    }

And here's the Modal class:

public partial class TalentInfo
{
    [Display(Name = "ID")]
    public int TalentID { get; set; }
    [Display(Name = "Talent's Name")]
    public string Talent_Name { get; set; }
    [Display(Name = "Email Address")]
    public string Talent_Email { get; set; }
    [Display(Name = "Self Promotion")]
    public string Talent_SelfPromotion { get; set; }
}

And here's the Repository:

public class RegisterRepository
{

    //SqlTransaction transaction = null;
    private SqlConnection con;
    //To Handle connection related activities
    private void connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        con = new SqlConnection(constr);


    }


    internal bool Register(TalentInfo model)
    {
        throw new NotImplementedException();

        connection();

        try
        {
            SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Talent_name", model.Talent_Name);
            com.Parameters.AddWithValue("@Talent_email", model.Talent_Email);
            com.Parameters.AddWithValue("@Talent_SelfPromotion", model.Talent_SelfPromotion);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                return true;
            }
            else
            {

                return false;
            }


        }

        catch
        {
            return Register(model);
        }
        finally
        {
            con.Close();
        }

    }


}

This is simply a compile error. You need to return a result in all paths of your code.

You have a missing return here

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
{
    if (ModelState.IsValid)
    {
        //you have lots of code here....
    }
    else
    {
        //you need to return something here....because (ModelState.IsValid) might be false
    }
}

There are 2 Errors in your code:

1) Return something when if (ModelState.IsValid) evaluates to false.

2) In the register method, remove this line :

throw new NotImplementedException();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM