Reading system.net/mailSettings/smtp from Web.config in Medium trust environment

这一生的挚爱 提交于 2019-12-02 23:55:56

The requirePemission attribute goes on the <configSections> grouping that matches the part fo the web.config you are having the security issue with.

additionally, you don't have to actually read the settings using code to send mail - you can simply use a blank SmtpClient:

 new SmtpClient.Send(MyMailMessage);

it will send using the settings from the config sections by default.

You can create a SmtpClient as some suggested, but that is a bit overkill - just read the sections directly.

var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
var host=section.Network.Host
Gerald

This works very well to me.

var smtp = new System.Net.Mail.SmtpClient();
var host = smtp.Host;
var ssl = smtp.EnableSsl;
var port = smtp.Port;

var credential = new System.Net.Configuration.SmtpSection().Network;
var username = credential.UserName;
var password = credential.Password;

Joys of coding eh... always 1000 ways to skin a fish

System.Net.Configuration.SmtpSection smtp = new System.Net.Configuration.SmtpSection();
string from = smtp.From;
//etc
System.Net.Configuration.SmtpNetworkElement nt = new System.Net.Configuration.SmtpNetworkElement();
string host = nt.Host;
//etc

To get the settings from the mail sections just create the mail objects.

var client = new SmtpClient();
var messageSettings = new MailMessage();

var host=client.Host;
//etc...

var fromAddress=messageSettings.From.Address;
//etc..

Config:

  <system.net>
    <mailSettings>
      <smtp from="xxxx@yahoo.com" deliveryMethod="Network" >
        <network host="smtp.mail.yahoo.com" port="587" enableSsl="true"
            userName="xxxx@yahoo.com" password="xxxxxxx"/>
      </smtp>     
    </mailSettings>
  </system.net>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!