Search code examples
c#asp.net-mvcasp.net-identity-2

ASP.NET MVC Usermanager SendEmailAsync: How to change sender email


I am using ASP.NET MVC5 with Identity 2, theres a file called IdentityConfig.cs which has EmailSerive that I have implemented like this:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        using (var client = new SmtpClient())
        {
            using (var mailMessage = new MailMessage("info@mydomain.com", message.Destination, message.Subject, message.Body))
            {
                mailMessage.IsBodyHtml = true;
                await client.SendMailAsync(mailMessage);
            }
        }
    }
}

With this setup, I am able to send user emails by calling this method on UserManager:

await UserManager.SendEmailAsync(user.Id, emailSubject, emailBody);

So far so good, but Id want the email to be sent from different senders depending on the subject. For instance, account registration/reset password will have sender account@mydomain.com, information inquiry emails will have sender info@mydomain.com, sales/order placement should have sender sales@mydomain.com.

Unfortunately, the method SendEmailAsync has no way to set the sender, and I have no idea how to achieve this in the EmailService either. Can anyone help with this problem? Is there a way to add an extension method to UserManager or EmailSerivce so I can optionally specify a different sender?


Solution

  • If I am in your place I would put all my emails in the web.config file and access it in a private method in the EmailService class that returns relevant email based on the subject and then call this method at the place of email parameter. e.g:

    public async Task SendAsync(IdentityMessage message) 
    {
        using (var client = new SmtpClient())
        {   
            //calling getEmail() instead of email
            using (var mailMessage = new MailMessage(getEmail(message.Subject),
        message.Destination, message.Subject, message.Body))
            {
                mailMessage.IsBodyHtml = true;
                await client.SendMailAsync(mailMessage);
            }
        }
    }
    
    private string getEmail(string subject) 
    {
        var emails = ConfigurationManager.AppSettings["Emails"];
        string[] emailAddresses = emails.Split(',');
        //your logic here
        return email;
    }