Search code examples
c#asp.net-mvc-4mvcmailer

Change From email address in MVCMailer 4.5


Does anyone know how to change the from email address in code to override the web.config settings.

What I'm trying to do is allow someone to complete an online form and when the recipicant receives the email, it will be from the senders email address.

But at the momment it is just displaying the default in web.config.

-----------------Web.config-------------------------

<smtp from="some-email@gmail.com" deliveryMethod="SpecifiedPickupDirectory">
                <network host="localhost" />
                <specifiedPickupDirectory pickupDirectoryLocation="c:\temp\"/>
            </smtp>

public virtual MvcMailMessage DirectotyEmail(string emailTo, string fromName, string arrivalDate, string departureDate, string message)
            {
            ViewBag.FromName        = fromName;
            ViewBag.ArrivalDate     = arrivalDate;
            ViewBag.DepartureDate   = departureDate;
            ViewBag.Message         = message;
            return Populate(x =>
            {
                x.Subject = "Accommodation Enquery form";
                x.ViewName = "DirectoryEmail";
                x.To.Add(emailTo.ToString());
                //x.From.Address("test@email.com");
                x.IsBodyHtml = true;
            });
            }

X-Sender: some-email@gmail.com << Need this to be the email that user entered when submitting form
X-Receiver: test@mail.com
MIME-Version: 1.0
From: some-email@gmail.com << Need this to be the email that user entered when submitting form
To: test@mail.com
Date: 26 Mar 2013 11:08:57 +0000
Subject: Accommodation Enquery form
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Solution

  • You can override the web config provided sender with the Sender property and the from address with the From property. Both properties expecting an MailAddress object, so you need to write:

    return Populate(x =>
    {
        x.Subject = "Accommodation Enquery form";
        x.ViewName = "DirectoryEmail";
        x.To.Add(emailTo.ToString());
        x.From = new MailAddress("test@email.com");
        x.Sender = new MailAddress("test@email.com");
        x.IsBodyHtml = true;
    });