0

I'm trying to send an email everytime the user creates a new comment. I've already installed the package Postal.MVC5

Comment Model

public int Id { get; set; }

    [Required]
    [MinLength(3)]
    [MaxLength(20)]
    public string Asunto { get; set; }
    [Required]
    public string Detalle { get; set; }
    [DataType(DataType.Date)]
    public DateTime Fecha { get; set; }
    [DataType(DataType.Time)]
    public DateTime Hora { get; set; }
    public  virtual Local local { get; set; }
    public virtual string username { get; set; }

NewCommentEmail Model

public class NewCommentEmail : Email
{
    public string To { get; set; }
    public string UserName { get; set; }
    public string Comment { get; set; }
}

Controller

 [HttpPost]
    public ActionResult AgregarComentario(NotasAdjuntas nota)
    {
        try
        {
            var localId = int.Parse(Request["LocalID"]);
            nota.username = Session["Username"].ToString();

            using (var db = new AutoContex())
            {
                nota.local = db.Locales.Find(localId);
                db.Entry(nota.local).Reference(p => p.Proveedor).Load();
                db.Notas.Add(nota);
                db.SaveChanges();
            }

            var email = new NewCommentEmail();
            email.To = "emilia.lasaga@pedidosya.com";
            email.UserName = nota.username;
            email.Comment = nota.Asunto;               
            email.Send();
            return RedirectToAction("Details", new { @id = localId });                
        }
        catch
        {
            return View();
        }
    }

I've also added this to the webconfig

<system.net>
<mailSettings>
  <smtp deliveryMethod="SpecifiedPickupDirectory">
    <specifiedPickupDirectory pickupDirectoryLocation="C:\Temp\" />
  </smtp>
</mailSettings>

The error I'm getting is: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:Couldn‌​'t make connection on time of execution in a NULL reference

The line that is getting the error is:

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

View

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Notas Adjuntas</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div>
        <ledgend>Datos del Local<ledgend>
                <div class="panel-title">Id</div>
                <div class="text-left">
                    <input type="Text" name="LocalID" id="LocalID" value="@ViewBag.Local.Id" />
                </div>
            <table class="table">
                <tr>
                    <th>Id</th>
                    <th>Viejo Id</th>
                    <th>Nombre</th>
                    <th>Unificado Con</th>
                    <th>Dirección</th>
                    <th>Telefono</th>
                    <th>Localidad</th>
                    <th>Provincia</th>
                    <th>Proveedor</th>
                    <th>Estado</th>

                    <th>Fecha Instalación</th>
                </tr>
                <tr>
                    <td>@ViewBag.Local.NuevoId</td>
                    <td>@ViewBag.Local.ViejoId</td>
                    <td>@ViewBag.Local.NombreComercio</td>
                    <td>@ViewBag.Local.UnificadoCon</td>
                    <td>@ViewBag.Local.Direccion</td>
                    <td>@ViewBag.Local.Telefono</td>
                    <td>@ViewBag.Local.Localidad</td>
                    <td>@ViewBag.Local.Provincia</td>
                    <td>@ViewBag.Local.Proveedor.Nombre</td>
                    <td>@ViewBag.Local.Estado.State</td>

                    <td>@ViewBag.Local.FechaInstalacion</td>
                </tr>
            </table>

    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Asunto, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Asunto, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Asunto, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
@Html.LabelFor(model => model.Detalle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.EditorFor(model => model.Detalle, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Detalle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Fecha, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Fecha, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Fecha, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Hora, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Hora, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Hora, "", new { @class = "text-danger" })
    </div>
</div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
mason
  • 31,774
  • 10
  • 77
  • 121
Syrup72
  • 116
  • 1
  • 12
  • 2
    Is there any more detail to the error? More to the message? Stack trace? Inner Exception? – mason Apr 20 '17 at 18:50
  • Detalles de la excepción: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: No se puede realizar enlace en tiempo de ejecución en una referencia NULL – Syrup72 Apr 20 '17 at 18:58
  • Can you translate that to English? Stack Overflow is an English website and it's hard to help you in another language. – mason Apr 20 '17 at 18:59
  • Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:Couldn't make connection on time of execution in a NULL reference – Syrup72 Apr 20 '17 at 19:03
  • And which line throws the error? – mason Apr 20 '17 at 19:08
  • @Html.ValidationSummary(true, "", new { @class = "text-danger" }) (in the AgregarCommentario View) – Syrup72 Apr 20 '17 at 19:12
  • You didn't provide that line in your question. Please add the view to your question. But anyways, I suspect it's taking issue with the "". You probably need to add an actual property name. Not sure that it makes sense to put a validation summary in your email either.... – mason Apr 20 '17 at 19:13
  • I've added more details in the question, I didn't understand the actual property name – Syrup72 Apr 20 '17 at 19:19
  • Why are you including all this validation data in the email? Why not strip it all out? Or is this view not the view that you're emailing? – mason Apr 20 '17 at 19:24
  • Replace ValidationMessageFor lines just for @Html.ValidationMessageFor(model => model.Asunto). The same goes with @Html.ValidationSummary(true), just let @Html.ValidationSummary() – Federico Alecci Apr 20 '17 at 19:33
  • I'm still getting the same error at @Html.ValidationSummary() – Syrup72 Apr 20 '17 at 19:42

1 Answers1

0

I was able send the email through smtps

It wasn't the frist approach I was looking for (I wanted to do it through Postal.MVC5)

What I did was this:

New Class to create the email

    using System.Net.Mail;
using System.Net;

namespace AutoPlanMCV.Models
{
    public class NewCommentEmail 
    {
        public static string GmailUsername { get; set; }
        public static string GmailPassword { get; set; }
        public static string GmailHost { get; set; }
        public static int GmailPort { get; set; }
        public static bool GmailSSL { get; set; }

        public string ToEmail { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public bool IsHtml { get; set; }

        static NewCommentEmail()
        {
            GmailHost = "smtp.gmail.com";
            GmailPort = 25; // Gmail can use ports 25, 465 & 587; but must be 25 for medium trust environment.
            GmailSSL = true;
        }

        public void Send()
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Host = GmailHost;
            smtp.Port = GmailPort;
            smtp.EnableSsl = GmailSSL;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(GmailUsername, GmailPassword);

            using (var message = new MailMessage(GmailUsername, ToEmail))
            {
                message.Subject = Subject;
                message.Body = Body;
                message.IsBodyHtml = IsHtml;
                smtp.Send(message);
            }
        }

}

Controller

public ActionResult AgregarComentario(NotasAdjuntas nota)
    {

        try
        {

            var localId = int.Parse(Request["LocalID"]);
            nota.username = Session["Username"].ToString();

            using (var db = new AutoContex())
            {
                nota.local = db.Locales.Find(localId);
                db.Entry(nota.local).Reference(p => p.Proveedor).Load();
                db.Notas.Add(nota);
                db.SaveChanges();

                if (nota.Asunto.Contains("capa"))
                {
                    NewCommentEmail.GmailUsername = "youremail@gmail.com";
                    NewCommentEmail.GmailPassword = "yourpassword";

                    NewCommentEmail mailer = new NewCommentEmail();
                    mailer.ToEmail = "Emailto@gmail.com";
                    mailer.Subject = nota.Asunto;
                    mailer.Body = nota.local.NuevoId + " --  --" + nota.local.NombreComercio + "<br />" + nota.Detalle + "<br /> Hora:" + nota.Hora;
                    mailer.IsHtml = true;
                    mailer.Send();
                }
            }

            return RedirectToAction("Details", new { @id = localId });

        }
        catch
        {
            return View();
        }

    }

I removed what I had in the webconfig, and I didn't edit my view. I didn't receive any errors after that

Syrup72
  • 116
  • 1
  • 12