//

SEND EMAIL IN UMBRACO

Sending email is a common functionality of any client-facing website. Is it possible to be implemented in Umbraco without a plugin? Yes, and I’m going to demonstrate how to implement such functionality.

In your ASP.NET MVC solution, open App_Code folder. Create a new surface controller called EmailController, extending SurfaceController

using System.Web;
using System.Web.Mvc;
using System.Net.Mail;

public class AppointmentController : Umbraco.Web.Mvc.SurfaceController
{
}

Add a new method, SendMail. Annotate it with HttpPost attribute.

[HttpPost]
public int SendMail()
{  
}

Now you have to create a model for this method. Create a folder called Models in App_Code folder and create a new file for this. Let's name it ContactModel.

using System.ComponentModel.DataAnnotations;

public class ContactModel
{
    [Required]
    public string Name { get; set; }
 
    [Required]
    public string Email { get; set; }
     
    [Required]
    public string Message { get; set; }
 
}

This model will consist of 3 properties: Name, Email and Message which are the name of the sender, the email address of the sender,and the body of the message. You could create any property you like here in this model. Now let's add the functionality to the method. You can use your SMTP details to replace smtp.example.com here.

[HttpPost]
public int SendMail(ContactModel model)
{    
    if (!ModelState.IsValid)
    {
        try 
        {
            var fromAddress = new MailAddress("abc@example.com", "From Name");
         
            var toAddress = new MailAddress(model.Email, "To Name");

            const string fromPassword = "password";
            string subject = "subject";
            string body = model.Message;

            var smtp = new SmtpClient
                        {
                            Host = "smtp.example.com",
                            Port = 587,
                            EnableSsl = true,
                            DeliveryMethod = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = false,
                            Credentials = new NetworkCredential(fromAddress, fromPassword)
                        };
   
            using (var message = new MailMessage(fromAddress.Address, toAddress.Address)
                        {
                            Subject = subject,
                            Body = body
                        })
            {
                smtp.Send(message);
                TempData.Add("Success", true);
            }
        }
        catch(Exception ex)
        {
            return -1;   
        }        
    }
    return 1;        
}

Now you can call this method from your client side code and off you go. Happy emailing!