In many older Umbraco projects, you might encounter custom code for sending emails using classes like SmtpClient. While this approach works, there is a more modern and future-proof alternative: leveraging Umbraco’s built-in services. By using Umbraco’s abstractions, you not only simplify your code but also make it more adaptable to future platform updates.
Below is an example of a common custom implementation you might come across:
public interface IEmailService
{
Task SendEmailAsync(string recipient, string subject, string body);
}
public class SmtpEmailService : IEmailService
{
private readonly string _from;
private readonly string _host;
private readonly int _port;
private readonly string _username;
private readonly string _password;
public SmtpEmailService(IConfiguration configuration)
{
var smtpSettings = configuration.GetSection("Umbraco:CMS:Global:Smtp");
_from = smtpSettings["From"];
_host = smtpSettings["Host"];
_port = int.Parse(smtpSettings["Port"]);
_username = smtpSettings["Username"];
_password = smtpSettings["Password"];
}
public async Task SendEmailAsync(string recipient, string subject, string body)
{
using var smtpClient = new SmtpClient(_host, _port)
{
Credentials = new NetworkCredential(_username, _password),
EnableSsl = true
};
var mailMessage = new MailMessage(_from, recipient, subject, body);
await smtpClient.SendMailAsync(mailMessage);
}
}
While functional, this approach involves significant custom logic to configure and handle SMTP settings.
Starting with Umbraco 9, you can use the built-in IEmailSender service, which simplifies email sending and integrates seamlessly with Umbraco’s configuration.
public interface IEmailSender
{
Task SendAsync(EmailMessage message, string emailType);
Task SendAsync(EmailMessage message, string emailType, bool enableNotification);
bool CanSendRequiredEmail();
}
With IEmailSender, there is no need to manually manage SMTP settings. These can be retrieved directly from Umbraco’s configuration:
IOptions<GlobalSettings> globalSettings;
var from = globalSettings.Value.Smtp?.From ?? throw new ArgumentNullException(nameof(globalSettings.Value.Smtp.From));
You can send a basic email by injecting IEmailSender. Simply create an email message and send it:
var emailMessage = new EmailMessage(_fromEmail, receiver.Email, subject, body, true);
var result = _emailSender.SendAsync(emailMessage, "Newsletter");
This approach eliminates the need to manage low-level SMTP configurations, streamlining the logic and aligning with Umbraco’s built-in standards.
By switching to IEmailSender, you save time, reduce potential bugs, and ensure your email logic aligns with Umbraco’s ecosystem.