在 web.config 中设置多个 SMTP 设置?

发布于 2024-10-06 08:25:41 字数 250 浏览 0 评论 0原文

我正在构建一个应用程序,需要在发送电子邮件时动态/编程地了解并使用不同的 SMTP 设置。

我习惯使用 system.net/mailSettings 方法,但据我了解,这种方法一次只允许一个 SMTP 连接定义,由 SmtpClient() 使用。

但是,我需要更多类似连接字符串的方法,在其中我可以根据键/名称提取一组设置。

有什么建议吗?我愿意跳过传统的 SmtpClient/mailSettings 方法,我认为必须......

I am building an app that needs to dynamically/programatically know of and use different SMTP settings when sending email.

I'm used to using the system.net/mailSettings approach, but as I understand it, that only allows one SMTP connection definition at a time, used by SmtpClient().

However, I need more of a connectionStrings-like approach, where I can pull a set of settings based on a key/name.

Any recommendations? I'm open to skipping the tradintional SmtpClient/mailSettings approach, and I think will have to...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

孤寂小茶 2024-10-13 08:25:41

我需要根据环境在 web.config 中设置不同的 smtp 配置:开发、登台和生产。

这是我最终使用的:

在 web.config 中:

<configuration>
  <configSections>
    <sectionGroup name="mailSettings">
      <section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
      <section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
      <section name="smtp_3" type="System.Net.Configuration.SmtpSection"/>
    </sectionGroup>
  </configSections>
  <mailSettings>
    <smtp_1 deliveryMethod="Network" from="[email protected]">
      <network host="..." defaultCredentials="false"/>
    </smtp_1>
    <smtp_2 deliveryMethod="Network" from="[email protected]">
      <network host="1..." defaultCredentials="false"/>
    </smtp_2>
    <smtp_3 deliveryMethod="Network" from="[email protected]">
      <network host="..." defaultCredentials="false"/>
    </smtp_3>
  </mailSettings>
</configuration>

然后在代码中:

return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_2");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_3");

I needed to have different smtp configurations in the web.config depending on the environment: dev, staging and production.

Here's what I ended up using:

In web.config:

<configuration>
  <configSections>
    <sectionGroup name="mailSettings">
      <section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
      <section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
      <section name="smtp_3" type="System.Net.Configuration.SmtpSection"/>
    </sectionGroup>
  </configSections>
  <mailSettings>
    <smtp_1 deliveryMethod="Network" from="[email protected]">
      <network host="..." defaultCredentials="false"/>
    </smtp_1>
    <smtp_2 deliveryMethod="Network" from="[email protected]">
      <network host="1..." defaultCredentials="false"/>
    </smtp_2>
    <smtp_3 deliveryMethod="Network" from="[email protected]">
      <network host="..." defaultCredentials="false"/>
    </smtp_3>
  </mailSettings>
</configuration>

Then in code:

return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_2");
return (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_3");
独留℉清风醉 2024-10-13 08:25:41
SmtpSection smtpSection =  (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");

SmtpClient smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
smtpClient.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
SmtpSection smtpSection =  (SmtpSection)ConfigurationManager.GetSection("mailSettings/smtp_1");

SmtpClient smtpClient = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
smtpClient.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
我ぃ本無心為│何有愛 2024-10-13 08:25:41

这就是我使用它的方式,它对我来说效果很好(设置类似于 Mikko 答案):

  1. 首先设置配置部分:

    <前><代码><配置>;
    <配置部分>
    <节名称=“默认”类型=“System.Net.Configuration.SmtpSection”/>
    <节名称=“邮件”类型=“System.Net.Configuration.SmtpSection”/>
    <节名称=“partners”类型=“System.Net.Configuration.SmtpSection”/>

    <邮件设置>
    <默认传递方法=“网络”>
    <网络主机=“smtp1.test.org”端口=“587”enableSsl=“true”
    用户名=“测试” 密码=“测试”/>

    <邮件传递方法=“网络”>
    <网络主机=“smtp2.test.org”端口=“587”enableSsl=“true”
    用户名=“测试” 密码=“测试”/>

    <合作伙伴deliveryMethod="网络">
    <网络主机=“smtp3.test.org”端口=“587”enableSsl=“true”
    用户名=“测试” 密码=“测试”/>

  2. 那么最好创建某种包装器。请注意,下面的大部分代码取自 SmtpClient 此处<的 .NET 源代码/a>

    公共类 CustomSmtpClient
    {
        私有只读 SmtpClient _smtpClient;
    
        公共 CustomSmtpClient(字符串部分名称 =“默认”)
        {
            SmtpSection 部分 = (SmtpSection)ConfigurationManager.GetSection("mailSettings/" + 部分名称);
    
            _smtpClient = new SmtpClient();
    
            if(部分!= null)
            {
                if (section.Network != null)
                {
                    _smtpClient.Host = 部分.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 = 部分.DeliveryMethod;
                if (section.SpecifiedPickupDirectory!= null &§ion.SpecifiedPickupDirectory.PickupDirectoryLocation != null)
                    _smtpClient.PickupDirectoryLocation =section.SpecifiedPickupDirectory.PickupDirectoryLocation;
            }
        }
    
        公共无效发送(MailMessage消息)
        {
            _smtpClient.Send(消息);
        }
    

    }

  3. 然后只需发送电子邮件:

    new CustomSmtpClient("mailings").Send(new MailMessage())

This is how i use it and it works fine for me (settings are similar to Mikko answer):

  1. First set up config sections:

    <configuration>
      <configSections>
        <sectionGroup name="mailSettings">
          <section name="default" type="System.Net.Configuration.SmtpSection" />
          <section name="mailings" type="System.Net.Configuration.SmtpSection" />
          <section name="partners" type="System.Net.Configuration.SmtpSection" />
        </sectionGroup>
      </configSections>
    <mailSettings>
      <default deliveryMethod="Network">
        <network host="smtp1.test.org" port="587" enableSsl="true"
               userName="test" password="test"/>
      </default>
      <mailings deliveryMethod="Network">
        <network host="smtp2.test.org" port="587" enableSsl="true"
               userName="test" password="test"/>
      </mailings>
    <partners deliveryMethod="Network">
      <network host="smtp3.test.org" port="587" enableSsl="true"
               userName="test" password="test"/>
    </partners>
    

  2. Then it would be the best to create a some sort of wrapper. Note that most of code below was taken from .NET source code for SmtpClient here

    public class CustomSmtpClient
    {
        private readonly SmtpClient _smtpClient;
    
        public CustomSmtpClient(string sectionName = "default")
        {
            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. Then simply send email:

    new CustomSmtpClient("mailings").Send(new MailMessage())

你没皮卡萌 2024-10-13 08:25:41

这可能对某人有帮助,也可能没有帮助,但如果您在这里寻找用于多个 smtp 配置的 Mandrill 设置,我最终创建了一个继承自 SmtpClient 类的类,遵循此人的代码,这非常好: https://github.com/iurisilvio/mandrill-smtp.NET

    /// <summary>
/// Overrides the default SMTP Client class to go ahead and default the host and port to Mandrills goodies.
/// </summary>
public class MandrillSmtpClient : SmtpClient
{

    public MandrillSmtpClient( string smtpUsername, string apiKey, string host = "smtp.mandrillapp.com", int port = 587 )
        : base( host, port )
    {

        this.Credentials = new NetworkCredential( smtpUsername, apiKey );

        this.EnableSsl = true;
    }
}

下面是如何调用它的示例:

        [Test]
    public void SendMandrillTaggedEmail()
    {

        string SMTPUsername = _config( "MandrillSMTP_Username" );
        string APIKey = _config( "MandrillSMTP_Password" );

        using( var client = new MandrillSmtpClient( SMTPUsername, APIKey ) ) {

            MandrillMailMessage message = new MandrillMailMessage() 
            { 
                From = new MailAddress( _config( "FromEMail" ) ) 
            };

            string to = _config( "ValidToEmail" );

            message.To.Add( to );

            message.MandrillHeader.PreserveRecipients = false;

            message.MandrillHeader.Tracks.Add( ETrack.opens );
            message.MandrillHeader.Tracks.Add( ETrack.clicks_all );

            message.MandrillHeader.Tags.Add( "NewsLetterSignup" );
            message.MandrillHeader.Tags.Add( "InTrial" );
            message.MandrillHeader.Tags.Add( "FreeContest" );


            message.Subject = "Test message 3";

            message.Body = "love, love, love";

            client.Send( message );
        }
    }

This may or may not help someone but in case you got here looking for Mandrill setup for multiple smtp configurations I ended up creating a class that inherits from the SmtpClient class following this persons code here which is really nice: https://github.com/iurisilvio/mandrill-smtp.NET

    /// <summary>
/// Overrides the default SMTP Client class to go ahead and default the host and port to Mandrills goodies.
/// </summary>
public class MandrillSmtpClient : SmtpClient
{

    public MandrillSmtpClient( string smtpUsername, string apiKey, string host = "smtp.mandrillapp.com", int port = 587 )
        : base( host, port )
    {

        this.Credentials = new NetworkCredential( smtpUsername, apiKey );

        this.EnableSsl = true;
    }
}

Here's an example of how to call this:

        [Test]
    public void SendMandrillTaggedEmail()
    {

        string SMTPUsername = _config( "MandrillSMTP_Username" );
        string APIKey = _config( "MandrillSMTP_Password" );

        using( var client = new MandrillSmtpClient( SMTPUsername, APIKey ) ) {

            MandrillMailMessage message = new MandrillMailMessage() 
            { 
                From = new MailAddress( _config( "FromEMail" ) ) 
            };

            string to = _config( "ValidToEmail" );

            message.To.Add( to );

            message.MandrillHeader.PreserveRecipients = false;

            message.MandrillHeader.Tracks.Add( ETrack.opens );
            message.MandrillHeader.Tracks.Add( ETrack.clicks_all );

            message.MandrillHeader.Tags.Add( "NewsLetterSignup" );
            message.MandrillHeader.Tags.Add( "InTrial" );
            message.MandrillHeader.Tags.Add( "FreeContest" );


            message.Subject = "Test message 3";

            message.Body = "love, love, love";

            client.Send( message );
        }
    }
平定天下 2024-10-13 08:25:41

只需在准备发送邮件时传入相关详细信息,并将所有这些设置存储在 web.config 的应用程序设置中。

例如,在 web.config 中创建不同的 AppSettings(如“EmailUsername1”等),您将能够完全单独调用它们,如下所示:

        System.Net.Mail.MailMessage mail = null;
        System.Net.Mail.SmtpClient smtp = null;

        mail = new System.Net.Mail.MailMessage();

        //set the addresses
        mail.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["Email1"]);
        mail.To.Add("[email protected]");

        mail.Subject = "The secret to the universe";
        mail.Body = "42";

        //send the message
        smtp = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings["YourSMTPServer"]);

        //to authenticate, set the username and password properites on the SmtpClient
        smtp.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["EmailUsername1"], System.Configuration.ConfigurationManager.AppSettings["EmailPassword1"]);
        smtp.UseDefaultCredentials = false;
        smtp.Port = System.Configuration.ConfigurationManager.AppSettings["EmailSMTPPort"];
        smtp.EnableSsl = false;

        smtp.Send(mail);

Just pass in the relevant details when you are ready to send the mail, and store all of those settings in your app setttings of web.config.

For example, create the different AppSettings (like "EmailUsername1", etc.) in web.config, and you will be able to call them completely separately as follows:

        System.Net.Mail.MailMessage mail = null;
        System.Net.Mail.SmtpClient smtp = null;

        mail = new System.Net.Mail.MailMessage();

        //set the addresses
        mail.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["Email1"]);
        mail.To.Add("[email protected]");

        mail.Subject = "The secret to the universe";
        mail.Body = "42";

        //send the message
        smtp = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings["YourSMTPServer"]);

        //to authenticate, set the username and password properites on the SmtpClient
        smtp.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["EmailUsername1"], System.Configuration.ConfigurationManager.AppSettings["EmailPassword1"]);
        smtp.UseDefaultCredentials = false;
        smtp.Port = System.Configuration.ConfigurationManager.AppSettings["EmailSMTPPort"];
        smtp.EnableSsl = false;

        smtp.Send(mail);
半暖夏伤 2024-10-13 08:25:41

我有同样的需求,标记的答案对我有用。

我在 web.config 中进行了这些更改

      <configSections>
        <sectionGroup name="mailSettings2">
          <section name="noreply" type="System.Net.Configuration.SmtpSection"/>
        </sectionGroup>
        <section name="othersection" type="SomeType" />
      </configSections>

      <mailSettings2>
        <noreply deliveryMethod="Network" from="[email protected]"> // noreply, in my case - use your mail in the condition bellow
          <network enableSsl="false" password="<YourPass>" host="<YourHost>" port="25" userName="<YourUser>" defaultCredentials="false" />
        </noreply>
      </mailSettings2>
      ... </configSections>

然后,我有一个发送邮件的线程:

SomePage.cs

private bool SendMail(String From, String To, String Subject, String Html)
    {
        try
        {
            System.Net.Mail.SmtpClient SMTPSender = null;

            if (From.Split('@')[0] == "noreply")
            {
                System.Net.Configuration.SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings2/noreply");
                SMTPSender = new System.Net.Mail.SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
                SMTPSender.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                Message.From = new System.Net.Mail.MailAddress(From);

                Message.To.Add(To);
                Message.Subject = Subject;
                Message.Bcc.Add(Recipient);
                Message.IsBodyHtml = true;
                Message.Body = Html;
                Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                SMTPSender.Send(Message);

            }
            else
            {
                SMTPSender = new System.Net.Mail.SmtpClient();
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                Message.From = new System.Net.Mail.MailAddress(From);

                SMTPSender.EnableSsl = SMTPSender.Port == <Port1> || SMTPSender.Port == <Port2>;

                Message.To.Add(To);
                Message.Subject = Subject;
                Message.Bcc.Add(Recipient);
                Message.IsBodyHtml = true;
                Message.Body = Html;
                Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                SMTPSender.Send(Message);
            }
        }
        catch (Exception Ex)
        {
            Logger.Error(Ex.Message, Ex.GetBaseException());
            return false;
        }
        return true;
    }

谢谢 =)

I had the same need and the marked answer worked for me.

I made these changes in the

web.config:

      <configSections>
        <sectionGroup name="mailSettings2">
          <section name="noreply" type="System.Net.Configuration.SmtpSection"/>
        </sectionGroup>
        <section name="othersection" type="SomeType" />
      </configSections>

      <mailSettings2>
        <noreply deliveryMethod="Network" from="[email protected]"> // noreply, in my case - use your mail in the condition bellow
          <network enableSsl="false" password="<YourPass>" host="<YourHost>" port="25" userName="<YourUser>" defaultCredentials="false" />
        </noreply>
      </mailSettings2>
      ... </configSections>

Then, I have a thread that send the mail:

SomePage.cs

private bool SendMail(String From, String To, String Subject, String Html)
    {
        try
        {
            System.Net.Mail.SmtpClient SMTPSender = null;

            if (From.Split('@')[0] == "noreply")
            {
                System.Net.Configuration.SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings2/noreply");
                SMTPSender = new System.Net.Mail.SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
                SMTPSender.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                Message.From = new System.Net.Mail.MailAddress(From);

                Message.To.Add(To);
                Message.Subject = Subject;
                Message.Bcc.Add(Recipient);
                Message.IsBodyHtml = true;
                Message.Body = Html;
                Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                SMTPSender.Send(Message);

            }
            else
            {
                SMTPSender = new System.Net.Mail.SmtpClient();
                System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
                Message.From = new System.Net.Mail.MailAddress(From);

                SMTPSender.EnableSsl = SMTPSender.Port == <Port1> || SMTPSender.Port == <Port2>;

                Message.To.Add(To);
                Message.Subject = Subject;
                Message.Bcc.Add(Recipient);
                Message.IsBodyHtml = true;
                Message.Body = Html;
                Message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
                Message.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
                SMTPSender.Send(Message);
            }
        }
        catch (Exception Ex)
        {
            Logger.Error(Ex.Message, Ex.GetBaseException());
            return false;
        }
        return true;
    }

Thank you =)

痴情 2024-10-13 08:25:41

我最终构建了自己的自定义配置加载器,该加载器在 EmailService 类中使用。配置数据可以像连接字符串一样存储在 web.config 中,并按名称动态拉取。

I ended up building my own custom configuration loader that gets used in an EmailService class. Configuration data can be stored in web.config much like connection strings, and pulled by name dynamically.

烟花肆意 2024-10-13 08:25:41

看来您可以使用不同的 SMTP 字符串进行初始化。

SmtpClient 客户端 = new SmtpClient(服务器);

http://msdn.microsoft.com/en-us/library/k0y6s613.aspx

我希望这就是您正在寻找的。

It seems that you can initialize using different SMTP strings.

SmtpClient client = new SmtpClient(server);

http://msdn.microsoft.com/en-us/library/k0y6s613.aspx

I hope that is what you are looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文