0

Hi I am having difficulties sending email to registered users.I get exception error in the line:

msg.To.Add(new MailAddress(newsletter.AspNetUser.Email));

Error:

An exception of type 'System.NullReferenceException' occurred in MVCHarmony.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

Following is my code.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "NewsLetterId,Headerline,Description,Photo,NewsletterFile,Id")] Newsletter newsletter, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {


            MailMessage msg = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            StringBuilder sb = new StringBuilder();



            msg.From = new MailAddress("abc@hotmail.com");
            msg.To.Add(new MailAddress(newsletter.AspNetUser.Email));
            msg.Subject = "Newsletter";

            if (file != null && file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                var attachment = new Attachment(file.InputStream, fileName);

                msg.Attachments.Add(attachment);
            }

            msg.IsBodyHtml = false;


            sb.Append("" + newsletter.Headerline);
            sb.Append(Environment.NewLine);

            sb.Append("" + newsletter.Description);
            sb.Append(Environment.NewLine);
            msg.Body = sb.ToString();

            smtp.Host = "smtp.live.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.Credentials = new System.Net.NetworkCredential("abc@hotmail.com", "*******");
            smtp.Send(msg);


            db.Newsletters.Add(newsletter);
            db.SaveChanges();
            msg.Dispose();

enter image description here

user3810794
  • 263
  • 2
  • 6
  • 23
  • So... what's the problem? – Dai Jul 07 '14 at 02:12
  • i get following error :An exception of type 'System.NullReferenceException' occurred in MVCHarmony.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. – user3810794 Jul 07 '14 at 02:14
  • Good, add that in the question please. And if a line number is provided by the stacktrace, please post the line pointed by the stack trace too. – Unihedron Jul 07 '14 at 02:29
  • Where do you instantiate the db variable? – Jeroen1984 Jul 07 '14 at 08:43

0 Answers0