EzDevInfo.com

postal.js

JavaScript pub/sub library supporting advanced subscription features, and several helpful add-ons. If & Else just an anonymous function waiting to discover its inner closure

Color the postal code area in google maps api?

I want to show each postal code differently by having border around it and color inside its area. I am using google maps api service in js.


Source: (StackOverflow)

MVC 5 Using POSTAL with Models

I am trying to use Postal in Mvc.5.2.3 and Razor.3.2.3 in Visual studio Ultimate 2013, I have many forms to generate for this project and would like to use Views as i would like to Post content to a database as well as send an email out with the information from the form using Postal. I am also creating partial Views for the header and footer so they are always the same and only the content of the email is changed by what forms are used. The email that will be sent will be to the sales department for review, a second email needs to be sent to the person that filled out the form saying thank you and showing the information they sent with the form. I hope this makes sense. I had the database working properly but had so much trouble getting the email system to work i have just started over and just trying to get the email system working properly.

My Model

    using Postal;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;


    namespace APP.Models.Forms.Company
    {


        public class ContactEmail : Email
        {
          public ContactEmail() : base("Contact")
          { }

          public int ContactId { get; set; }
          public Guid TicketId { get; set; }

          [Required(ErrorMessage = "Please Enter your First Name!")]
          [StringLength(100, MinimumLength = 3)]
          [DisplayName("First Name")]
          [Display(Order = 1)]
          public string FirstName { get; set; }

          [Required(ErrorMessage = "Please Enter your Last Name!")]
          [StringLength(100, MinimumLength = 3)]
          [DisplayName("Last Name")]
          [Display(Order = 2)]
          public string LastName { get; set; }

          [DisplayName("Business Name")]
          [Display(Order = 3)]
          public string BusinessName { get; set; }


          [Required(ErrorMessage = "You have not entered a phone numer, Please enter your phone number so we can get back to you!")]
          [DataType(DataType.PhoneNumber)]
          [DisplayName("Phone Number")]
          [RegularExpression(@"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$", ErrorMessage = "Please enter proper format of one of the following: (555)555-5555, 555-555-5555, 5555555555")]
          [StringLength(32)]
          [Display(Order = 4)]
          public string Phone { get; set; }

          [Required(ErrorMessage = "You have not entered an Email address, Please enter your email address!")]
          [DataType(DataType.EmailAddress)]
          [DisplayName("Email Address")]
          [MaxLength(50)]
          [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "The Email field is not valid, Please enter a valid email address!")]
          [Display(Order = 5)]
          public string UserEmailAddress { get; set; }

          [Required(ErrorMessage = "You have not entered a message, Please enter a message!")]
          [DataType(DataType.MultilineText)]
          [StringLength(2000)]
          [DisplayName("Message")]
          [Display(Order = 6)]
          public string Message { get; set; }

          public Source Source { get; set; }


          public HttpPostedFileBase Upload { get; set; }


          [Display(Name = "Full Name")]
          public string FullName
          {
              get
              {
                  return LastName + ", " + FirstName;
              }
          }

      }

  }

The Controler:

    using APP.Models;
    using APP.Models.Forms.Company;
    using Postal;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Net.Mail;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;

    namespace APP.Controllers
    {
        public class FormsController : Controller
        {
            private ApplicationDbContext db = new ApplicationDbContext();

            #region Main Forms Page
            // Forms Page Blank with unautherized access
            public ActionResult Index()
            {
                return View();
            }
            #endregion


            #region Contact_Form
            // GET: Forms/Create
            public ActionResult Contact()
            {

                return View();
            }

            // POST: Forms/Submit


            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Send(ContactEmail form)
            {

                var email = new Email("Contact")
                {
                    To = "webmaster@somedomain.com",
                    MyModel = ContactEmail //Says its a "type" but used like a variable.


                }
                email.Send();



            }



    #endregion

    #region Condo Form
    #endregion

    #region Personal Flood Form
    #endregion

    #region Home Insurance Form
    #endregion

    #region Renters Insurance Form
    #endregion

    #region WaterCraft Insurance Form
    #endregion

    #region Life Insurance Form
    #endregion

    #region Business Flood Form
    #endregion

    #region Business Risk Form
    #endregion

    #region Business Inland Marine Form
    #endregion

    #region Business Group Health Form
    #endregion

    #region Form
    #endregion

    #region Not Available Forms Page
    // Forms Page Blank with unautherized access
    public ActionResult Not_Available()
    {
        return View();
    }
    #endregion

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

Form View:

    @model APP.Models.Forms.Company.ContactEmail


    @{
        ViewBag.Title = "Create";
        Layout = "~/Views/Shared/_Layout_LandingPages.cshtml";
    }
    <div class="box">
        <h2>Contact Form</h2>


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

        <div class="form-horizontal">
            <h4>Contact LS Insurance</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="row">
        <div class="col-lg-6">
            <div class="form-group">
                @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-4" })
                <div class="col-md-8">
                    @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="form-group">
                @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-4" })
                <div class="col-md-8">
                    @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="col-lg-12">
            <div class="form-group">
                @Html.LabelFor(model => model.BusinessName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.BusinessName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.BusinessName, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="form-group">
                @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-4" })
                <div class="col-md-8">
                    @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="form-group">
                @Html.LabelFor(model => model.UserEmailAddress, htmlAttributes: new { @class = "control-label col-md-4" })
                <div class="col-md-8">
                    @Html.EditorFor(model => model.UserEmailAddress, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.UserEmailAddress, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="col-lg-12">
            <div class="form-group">
                @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
                </div>
            </div>

        </div></div>


            <hr />
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Submit Form" class="btn btn-default" />&emsp;
                    <input type="reset" value="Reset Form" class="btn btn-default" />
                </div>
            </div>
        </div>
        }

        <div>


            @Html.ActionLink("Cancel", "Index", "Home")
        </div>
    </div>


    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

My email View is Contact.cshtml and is located in the email folder under Views.


Source: (StackOverflow)

Advertisements

when using Postal mail MVC 4 Razor Mobile View Engine generates error

I am using postal mail to send an order confirmation. It is an MVC4 project. The code was sending email confirmations correctly.

Recently, I have added MVC mobile to the project. Everything works - except when sending a confirmation email when the user is on a mobile device. This is the order confirmation class:

    public class OrderConfirmation : Postal.Email
    {
        public string email { get; set; }
        public string partyid { get; set; }
        public string GrouponCode { get; set; }
        public string originalpartyDate { get; set; }
        public string originalpartyStartTime { get; set; }
        public string originalpartyTitle { get; set; }
        public string originalOrderDate { get; set; }
        public bool GrouponWasUpgraded { get; set; }
        public decimal GrouponFaceValue { get; set; }
        public bool ClassCancelled { get; set; }
        public string firstname { get; set; }
        public string orderlink { get; set; }
    }

And then it gets called like this:

ci = new Email.OrderConfirmation
{
    ClassCancelled = false,
    email = Email,
    firstname = FirstName,
    orderlink = "https://website.com/Checkout/Archive?orderlinkid=" + OrderLinkId,
    originalpartyDate = DateStart.ToShortDateString(),
    originalpartyStartTime = DateStart.ToShortTimeString(),
    originalpartyTitle = odt.Party.Title,
    partyid = odt.PartyId.ToString()
 };
 Task task = ci.SendAsync();

In my Global.asax.cs file I detect the mobile devices, and insert the display modes, like this:

   protected void Application_Start()
   {
   DisplayModeProvider.Instance.Modes.Insert(0, new
        DefaultDisplayMode("Tablet")
        {
            ContextCondition = (ctx =>
            ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >= 0 ||
            ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0 &&
            ctx.Request.UserAgent.IndexOf("mobile", StringComparison.OrdinalIgnoreCase) < 1)
        });
        DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("iPhone")
            {
                ContextCondition = (ctx =>
                    ctx.GetOverriddenBrowser().IsMobileDevice ||
                    ctx.GetOverriddenUserAgent().IndexOf
                    ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0
                    )
            });
     /// omitted the rest of the (standard) code for brevity
    }

The error message I get is a generic "Object reference not set to an instance of an object." I have put the stack trace below, as well as an image of when the error code is generated.

Error screen capture when postal is generating the email view

iisexpress.exe Error: 0 : 4/15/2014 11:09:33 AMSystem.NullReferenceException: Object reference not set to an instance of an object.
   at application.MvcApplication.<Application_Start>b__1(HttpContextBase ctx) in c:\Dropbox\SourceCode\PUYF_NonTFS\PUYF_Website\Application\Global.asax.cs:line 132
   at System.Web.WebPages.DefaultDisplayMode.CanHandleContext(HttpContextBase httpContext)
   at System.Web.WebPages.DisplayModeProvider.<>c__DisplayClass6.<GetAvailableDisplayModesForContext>b__5(IDisplayMode mode)
   at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations)
   at System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)
   at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClassc.<FindView>b__a(IViewEngine e)
   at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
   at System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName)
   at Postal.EmailViewRenderer.CreateView(String viewName, ControllerContext controllerContext)
   at Postal.EmailViewRenderer.Render(Email email, String viewName)
   at Postal.EmailService.CreateMailMessage(Email email)
   at Postal.EmailService.SendAsync(Email email)
   at Postal.Email.SendAsync()
   at Application.Models.Order.SendConfirmation(ArtStoreEntities dbcontext) in    
c:\Dropbox\SourceCode\PUYF_NonTFS\PUYF_Website\Application\Models\Order.cs:line 134

It seems, when postal is generating the view, it hits the application_start in the global.asax file, and because the useragent properties are null - it generates the error. I tried putting a try catch block around the specific code in the application_start procedure - but that does not work.

I need help how to tell MVC or Postal not to bother with the displaymodes. Any suggestions?


Source: (StackOverflow)

How to include CSS styles inline in Razor view?

I am using Postal to render MVC Razor views and send them via email. I have a custom CSS that I have defined specifically for the email views. Currently I am including them as follows:

@Styles.Render("~/Content/EmailStyles.css")

However, this only includes the relative link to the stylesheet, which will not work in an email:

<link rel='nofollow' href="/Content/EmailStyles.css" rel="stylesheet"/>

I want to include the stylesheet inline so that it functions properly in the email. What is the best way to render the contents of a file-based resource within an MVC view?


Source: (StackOverflow)

Using Postal Library From the Business Layer

I have a website built using ASP.NET MVC3 which is layered as follows:

  • ProjectName.Shared (model + service contracts)
  • ProjectName.Infrastructure
  • ProjectName.Data
  • ProjectName.Data.Sql
  • ProjectName.Managers (Business layer)
  • ProjectName.Services (WCF services)
  • ProjectName.UI.Main (ASP.NET MVC3 application)

This is actually the structure I recently came up with after some refactoring. Unfortunately, there isn't complete separation between the UI and my business layer so this area could use some more refactoring - which I cannot do right now because I'm on a tight deadline.

As for now, my client has requested some new features which involve sending emails to users after some events happen. The way the website currently sends emails is by using the Postal library which is doing great so far. That happens from within the MVC web application which is different from the case I have for the new features...

The Problem:

I have the case where I need to let a private method inside my business layer to send out the emails to users. The reason why I cannot do that inside an Action method is because there are many code-paths that eventually end up calling this private method. So it's not really specific to one Action method.

Proposed Solution:

What I have in mind is to create an EmailsController which I can call its method through HTTP-POST calls from within my business layer. I would then pass on the parameters needed to send the email through the arguments of the Action method.

But I do find this solution to be kinda flawed and hacky. So I would really like to hear some thoughts on how to approach this problem.


Source: (StackOverflow)

jQuery Autocomplete City & Country based on zip code

I was wondering if anyone knew a good service for City and Country Lookup by postal code, I was using the ziptasic plugin from jQuery, but it only supports the US and I need to search within Canada, both would be great. I know google maps API is another method but I dont even know where to start.

Any help would be great!

Thanks


Source: (StackOverflow)

How to exclude cshtml from pre compilation during publish

I have cshtml files in a c# web forms project that I want to publish using a publish profile that has the options:

  • Allow precompiled site to be updateable = false

I am using Postal outside of ASP.net http://aboutcode.net/postal/outside-aspnet.html as the emails that are being sent are from a background process. This is using hangfire and is very similar to this: http://docs.hangfire.io/en/latest/tutorials/send-email.html

The problem is that the cshtml file is being precompiled when I dont want it to be and the resulting content of the file is:

This is a marker file generated by the precompilation tool, and should not be deleted!

I need the full contents of the original cshtml file and don't want the marker contents but I do also want to retain the setting of Allow precompiled site to be updateable = false so all other files can not be updated.

The only way I can see to do this is to have Allow precompiled site to be updateable = true

In short I want to deploy the cshtml in the same way that images files are when their build action is set to content.

Any ideas?

Edit: Seems that someone else has the exact same problem:

Is there a way to exclude certain .cshtm files, or an entire folder, from the 'precompile' option so that the .cshtml files can be used outside MVC?


Source: (StackOverflow)

Postal issue with Mvc 5.2

I'm trying to send emails within hangfire via postal(which I've downloaded with nuget). I've followed the example provided on strongly typed email data. After having added just the using statement using Postal; and inheritance from email:

using Postal;

namespace someNameSpace
{
    public class MyEmail : Email
    {
        public string From { get; set; }
        public string To { get; set; }
        public string Message { get; set; }
    }
}

I receive the error:

Could not load file or assembly |'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35|' or one of its dependencies. The located assembly|'s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)' errorDetails='System.IO.FileLoadException

I've searched around stack overflow and found the following solutions:

  • reinstall packages with nuget
  • redirect the assembly version

So far I've made sure that I have the redirects installed, tried changing the versions of some packages that postal depends on, and tried reinstalling Postal, Mvc, and RazorEngine packages.

I don't understand why the assembly redirect wouldn't take care of this issue. Here is my redirect from the config files:

 <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
 </dependentAssembly>

There is also a post on github following this issue.

The post mentions that this error only occurs if a "Strongly Typed Email Data" is used, so in the meantime, I'll try to avoid using that.

Any suggestions are greatly appreciated.


Source: (StackOverflow)

Entire email not being populated when sent - Postal, MVC 5

I'm using the Postal library to send emails from the contact page on the site I'm working on, it sends the email but not all items are being included in the email. I put a breakpoint in and stepped through the code and all the items are in the model being passed, but the template that's being emailed doesn't have all the data.

Here's the simple template (Contact.cshtml):

@model AccessorizeForLess.Models.ContactEmail
To: ****************@psychocoder.net
From: @Model.From
First Name: @Model.FirstName
Last Name: @Model.LastName
Subject: @Model.SelectedSubject
Message: @Model.Message

Here is the ContactEmail model

using AccessorizeForLess.ViewModels;
using Postal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AccessorizeForLess.Models
{
    public class ContactEmail : Email
    {
        public string To { get; set; }

        [DataType(DataType.EmailAddress)]
        [DisplayName("Email Address")]
        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Please enter a valid email address!")]
        [Required(ErrorMessage="Please provide your email address")]
        public string From { get; set; }

        [DisplayName("First Name")]
        [Required(ErrorMessage="Please provide your first name")]
        public string FirstName { get; set; }

        [DisplayName("Last Name")]
        [Required(ErrorMessage="Please provide your last name")]
        public string LastName { get; set; }

        [DisplayName("Subject")]
        [Required(ErrorMessage="Please select a subject")]
        public string SelectedSubject { get; set; }

        [DisplayName("Message")]
        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage="Please provide a message for the email")]
        public string Message { get; set; }

        public List<EmailSubjectViewModel> Subjects { get; set; }
    }
}

And the Send method in the ContactController:

public ActionResult Send(ContactEmail email)
{
    ContactEmail e = new ContactEmail();
    e.From = email.From;
    e.FirstName = email.FirstName;
    e.LastName = email.LastName;
    e.SelectedSubject = email.SelectedSubject;
    e.Message = email.Message;

    e.Send();
    return RedirectToAction("Index");
}

I've stepped through Send and the model being passed contains all the data, but the email that arrives only has last name, subject and message. First name and email address are missing for some reason.


Source: (StackOverflow)

Google Maps JS APIv3 - geocode returns the location of the INSEE code instead of the Postal Code

I recently developed a dealer geolocation platform with Google Maps V3 Js API, however I realized that when the user enters a zip code, geolocation is poor.

For example, if the user searches 13001 (1st district of Marseilles), geolocation is done on Aix-en-Provence (whose INSEE code is 13001). Ditto for 13007 (7th arrondissement of Marseille), returns Auriol 20km from Marseille.

It seems that this is the following piece of code that returns the wrong coordinates :

function GoogleGeocode(){
    geocoder = new google.maps.Geocoder();
    this.geocode = function(address, callbackFunction) {
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status === google.maps.GeocoderStatus.OK) {
            var result = {};
            result.latitude = results[0].geometry.location.lat();
            result.longitude = results[0].geometry.location.lng();                        
            callbackFunction(result);
          } else {
            if (settings.geocodeErrorAlert != "") {
              alert(settings.geocodeErrorAlert + status);
            }
            callbackFunction(null);
          }
        });
    };
  }

Do you have an explanation and a solution to solve this problem?

Thank you all


Source: (StackOverflow)

riemann.io add multi jar to EXTRA_CLASSPATH

Now i'm config riemann monitoring distributed system. I'm not config to use multi project for EXTRA_CLASSPATH in riemann config.

# /etc/sysconfig/riemann in centos 6.5

EXTRA_CLASSPATH=/path/riemann-extra-0.2.4.jar (This is jar in project link)

with

EXTRA_CLASSPATH=/path/postal-1.12-SNAPSHOT.jar (This is jar in project link)

[root@test-celk-server ~]# ps aux | grep riemann 
riemann  20536  124  8.4 6298660 677312 ?      Ssl  15:05   0:54 java -cp /usr/lib/riemann/riemann.jar:/home/setup/riemann-extra-master/target/riemann-extra-0.2.4.jar riemann.bin start /etc/riemann/riemann.config

Pls help config use multi classpath in riemann.io.


Source: (StackOverflow)

Unable to add new MVC 5 View Pages

After I installed Postal for MVC5 today, whenever I try to add a new MVC 5 View Page (Razor), I get the following error:

Error: this template attempted to load component assembly 'Microsoft.VisualStudio.Web.Mvc.5.0, Version=5.0.0.0, Culture=neutral, ...'

enter image description here

How can I fix this? I am not able to add new views to the project.


Source: (StackOverflow)

How to Set SMTP Client in POSTAL MVC not in WEB.Config

i have a problem when using POSTAL MVC in my Project. My hosting services company requires me to set smtp client config in code not in web config.

How to do that ?

I hope someone can give me a solution

Thank you.


Source: (StackOverflow)

Sending mail with Postal library in MVC 5

I'm using the Postal library to send emails from the contact page. I have the following code:

ContactEmail

using AccessorizeForLess.ViewModels;
using Postal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AccessorizeForLess.Models
{
    public class ContactEmail : Email
    {
        public string To { get; set; }

        [DataType(DataType.EmailAddress)]
        [DisplayName("Email Address")]
        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "The Email field is not valid, Please enter a valid email address!")]
        [Required(ErrorMessage="Email address is required.")]
        public string From { get; set; }

        [DisplayName("First Name")]
        [Required(ErrorMessage="Please provide your first name")]
        public string FirstName { get; set; }

        [DisplayName("Last Name")]
        [Required(ErrorMessage="Please provide your last name")]
        public string LastName { get; set; }

        [DisplayName("Subject")]
        [Required(ErrorMessage="Please select a topic")]
        public SelectList Subject { get; set; }
        public string SelectedSubject { get; set; }

        [DisplayName("Message")]
        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage="PLease provide a message for the email")]
        public string Message { get; set; }

        public List<EmailSubjectViewModel> Subjects { get; set; }
    }
}

EmailSubjectViewModel

namespace AccessorizeForLess.ViewModels
{
    public class EmailSubjectViewModel
    {
        public int Id { get; set; }
        public string Subject { get; set; }
    }
}

ContactController

public ActionResult Index()
        {
            List<EmailSubjectViewModel> Subjects = new List<EmailSubjectViewModel>()
            {
                new EmailSubjectViewModel(){Id=1, Subject="Website Issues"},
                new EmailSubjectViewModel(){Id=2, Subject="Order Issue"},
                new EmailSubjectViewModel(){Id=3, Subject="Product Question"},
                new EmailSubjectViewModel(){Id=4, Subject="Returns Questions"},
                new EmailSubjectViewModel(){Id=5, Subject="Other"}
            };

            ContactEmail email = new ContactEmail()
            {
                Subjects = Subjects
            };
            return View(email);
        }


        public ActionResult Send(ContactEmail email)
        {
            ContactEmail e = new ContactEmail();
            e.From = email.From;
            e.FirstName = email.FirstName;
            e.LastName = email.LastName;
            e.SelectedSubject = email.SelectedSubject;
            e.Message = email.Message;

            e.Send();
            return View();
        }

And last but not least my view:

@model AccessorizeForLess.Models.ContactEmail
@{
    ViewBag.Title = "Contact";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Contact</h2>

@using (Html.BeginForm("Send", "Contact", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>AccessorizeForLess.net&nbsp;&nbsp;&nbsp;
            <a rel='nofollow' href="https://www.facebook.com/accessorize5orless" target="_blank" title="Accessorize For Less On Facebook"><img src="~/Content/icon-facebook.png" /></a></h4>
        <div style="color:red;font-weight:bold;">@ViewBag.Message</div>

        <hr />
        @Html.ValidationSummary(true)

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.SelectedSubject, "Category", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedSubject, new SelectList(Model.Subjects, "Id", "Subject"), "- Please Select -")
                @Html.ValidationMessageFor(model => model.SelectedSubject)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Message, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Message, new { @cols = "25", @rows = "55" })
                @Html.ValidationMessageFor(model => model.Message)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Send" class="btn btn-default" />
            </div>
        </div>
  </div>


}

Oops almost forgot the section in my web.config

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="admin@accessorizeforless.net">
        <network host="smtp.gmail.com" port="587" enableSsl="true" defaultCredentials="true" userName="***********@gmail.com" password="**********" />
      </smtp>
    </mailSettings>
  </system.net>

Now when I fill out the form and click send I get the following error:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

I thought I was setting the authenticatioon credentials in the web.config?


Source: (StackOverflow)

Getting error when I send email using Postal MVC and SendAsync()

I'm trying to send an email using Postal MVC in my MVC controller. I want to send the email asynchronously and don't want to wait for the email to be sent before I return the View.

Here is the code that I'm trying to use.

        try
        {
            dynamic email = new Email("TestEmail");  //I have an Email View by this name
            email.To = "myemailaddress@domain.com";
            email.From = "recipientsaddress@domain.com";
            email.SendAsync();                      //email.Send() works fine
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

But I get this error "Failure sending mail."

Inner Exception System.InvalidOperationException:An asynchronous operation cannot be started at this time.Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle.If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. at System.Web.AspNetSynchronizationContext.OperationStarted() at System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState,SynchronizationContext syncContext) at System.Net.Mail.SmtpClient.SendAsync(MailMessage message,Object userToken)

If I replace the SendAsync() with Send() it works fine.

For completeness sake, this what my mailSettings look like in my Web.Config

  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="smtp.myisp.com" port="25" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>

Something seems to be wrong with sending the email asynchronously. Has anyone else come up with this problem and have a solution?

Or should I use another mailer like MvcMailer?

Please don't suggest that I should not send the email asynchronously. I want the response of my site to be fast and I find connecting to an email server to send an email during a sign up process to be a little non-responsive.


Source: (StackOverflow)