a blog for those who code

Wednesday 14 August 2019

Setting up MailJet SMTP Server in ASP.NET Core


I was looking for a good SMTP server for Asp.Net Core and came across MailJet whose pricing was reasonable. Once you sign up they will ask whether you would like to go with API or SMTP Relay. In this post we will look for setting SMTP Server Relay in ASP.NET Core application build on ASP.NET Boilerplate.


First thing first, we will be using MailKit which is an open source library which can be used in .Net framework, .Net Core etc. The good thing about Asp.Net Boilerplate code is that it has Mailkit enabled, we just have to supply the class.

First we will install Abp.MailKit package in our .Core project and then in the core module add depends on AbpMailKitModule as shown below

[DependsOn(typeof(AbpZeroCoreModule), typeof(AbpMailKitModule))]
public class LetsDiscCoreModule : AbpModule
{
}

To start with we will add the settings inside GetSettingDefinitions Method of AppSettingProvider Class under LetsDisc.Configuration. The method will look like :

public override IEnumerable<SettingDefinition> GetSettingDefinitions(SettingDefinitionProviderContext context)     
{
  return new[]
  {
    new SettingDefinition(EmailSettingNames.DefaultFromAddress, "My Email"),
    new SettingDefinition(EmailSettingNames.DefaultFromDisplayName, "My Name"),
    new SettingDefinition(EmailSettingNames.Smtp.Host, "abc.mailjet.com"),
    new SettingDefinition(EmailSettingNames.Smtp.Port, "465"),
    new SettingDefinition(EmailSettingNames.Smtp.EnableSsl, "true"),
    new SettingDefinition(EmailSettingNames.Smtp.UseDefaultCredentials, "false"),
    new SettingDefinition(EmailSettingNames.Smtp.UserName, 
                 _appConfiguration["Authentication:Mailjet:UserName"]),
    new SettingDefinition(EmailSettingNames.Smtp.Password, 
                _appConfiguration["Authentication:Mailjet:Password"])
  };     

Once done we have to Inject IEmailSender object and use it as shown below in our class,

await _emailSender.SendAsync(
    to: "to email",
    subject: "You have a new task!",
    body: $"A new task is assigned for you: ",
    isBodyHtml: true
);

Thus we can send our first mail using Mailjet in our ASP.NET Core project.

No comments:

Post a Comment