Web.Config'te Çoklu SMTP Ayarlarının Ayarlanması


1. Adımda farklı işlemler için kullanacağımız E-Posta hesaplarına ait SMTP bilgilerini Web.Config dosyasına tanımlıyoruz.

<configuration>
<configSections>
<sectionGroup name="mailSettings">
<section name="varsayilan" type="System.Net.Configuration.SmtpSection" />
<section name="pazarlama" type="System.Net.Configuration.SmtpSection" />
<section name="muhasebe" type="System.Net.Configuration.SmtpSection" />
</sectionGroup>
</configSections>
<mailSettings>
<varsayilan deliveryMethod="Network">
<network host="smtp1.test.org" port="587" enableSsl="true"
userName="info@domain.com" password="test"/>
</varsayilan>
<pazarlama deliveryMethod="Network">
<network host="smtp2.test.org" port="587" enableSsl="true"
userName="pazarlama@domain.com" password="test"/>
</pazarlama>
<muhasebe deliveryMethod="Network">
<network host="smtp3.test.org" port="587" enableSsl="true"
userName="muhasebe@domain.com" password="test"/>
</muhasebe>
</mailSettings>
</configuration>

2. Adımda farklı E-Posta hesapları ile gönderim yapabilecek olan Class'ı  aşağıdaki şekilde hazırlıyoruz.

public class CustomSmtpClient
{
private readonly SmtpClient _smtpClient;
public CustomSmtpClient(string sectionName = "varsayilan")
{
SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("mailSettings/" + sectionName);
_smtpClient = new SmtpClient();
if (section != null)
{
if (section.Network != null)
{
_smtpClient.Host = section.Network.Host;
_smtpClient.Port = section.Network.Port;
_smtpClient.UseDefaultCredentials = section.Network.DefaultCredentials;
_smtpClient.Credentials = new NetworkCredential(section.Network.UserName, section.Network.Password, section.Network.ClientDomain);
_smtpClient.EnableSsl = section.Network.EnableSsl;
if (section.Network.TargetName != null)
_smtpClient.TargetName = section.Network.TargetName;
}
_smtpClient.DeliveryMethod = section.DeliveryMethod;
if (section.SpecifiedPickupDirectory != null && section.SpecifiedPickupDirectory.PickupDirectoryLocation != null)
_smtpClient.PickupDirectoryLocation = section.SpecifiedPickupDirectory.PickupDirectoryLocation;
}
}
public void Send(MailMessage message)
{
_smtpClient.Send(message);
}

3. Adımda ise hazırladığımız Class'ı çağırıp Web.Config dosyasındaki istediğimiz SMTP bilgisi ile mail gönderim işlemini gerçekleştiriyoruz.

new CustomSmtpClient("varsayilan").Send(new MailMessage());
//veya
new CustomSmtpClient("pazarlama").Send(new MailMessage());
//veya
new CustomSmtpClient("muhasebe").Send(new MailMessage());

Share This Article

Comments (0)

Leave a Comment