I'm using the ASP.NET Boilerplate framework to send mail notification. I want to change the sender mail address based on the scenarios(one for Employees and another one for End Users)
Please advise me how to change sender mail address at run time (other than from default configuration).
mailSender.SendAsync(
to: toEmailAddress,
subject: mailSubject,
body: mailBody,
isBodyHtml: true);
Thanks in advance.
Here are 2 ways:
IEmailSender
has an overloaded method that takes in a from
parameter:
mailSender.SendAsync(
from: isEmployee ? employeeSenderEmailAddress : endUserSenderEmailAddress,
to: toEmailAddress,
subject: mailSubject,
body: mailBody,
isBodyHtml: true);
You can subclass SmtpEmailSenderConfiguration
, inject IAbpSession
and override UserName
getter. This way, you abstract the email address logic.
public override string UserName
{
get
{
var isEmployee = AbpSession.UserId == 0; // Example
return isEmployee ? employeeSenderEmailAddress : endUserSenderEmailAddress;
}
}
Remember to replace the services in the PreInitialize
method of your module:
Configuration.ReplaceService(typeof(IEmailSenderConfiguration), () =>
{
IocManager.IocContainer.Register(
Component.For<IEmailSenderConfiguration, ISmtpEmailSenderConfiguration>()
.ImplementedBy<MySmtpEmailSenderConfiguration>()
.LifestyleTransient()
);
});