Asp.net(C#) 发送Email的用法

我们常写web程序都会用到发邮件的功能,这里也就是做个备案。其实这个功能很简单,首先在Web.config 的<configuration>里加入:

 <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="[email protected]" >
        <network host="localhost" defaultCredentials="false" userName="[email protected]" password="passowrd"/>
      </smtp>
    </mailSettings>
  </system.net>

程序code:

SmtpSection cfg = ConfigurationManager.GetSection(@"system.net/mailSettings/smtp") as SmtpSection;
SmtpNetworkElement smtElement = cfg.Network;
//实例化一个邮件消息对象     
MailMessage email; 
string displayName="xxxx"; //email中的显示名
if (string.IsNullOrEmpty(displayName))
{
	email = new MailMessage(_FromEmail, _ToEmail);
}
else
{
	MailAddress fromMail = new MailAddress(_FromEmail, displayName, System.Text.Encoding.UTF8);
	MailAddress toMail = new MailAddress(_ToEmail);
	email = new MailMessage(fromMail, toMail);
	//email.Sender = new MailAddress(_FromEmail, displayName, System.Text.Encoding.UTF8);
}
email.IsBodyHtml = isHtml;
email.Body = _Body;
email.Subject = _Subject;
email.BodyEncoding = System.Text.Encoding.UTF8;
//实例化smtp客服端对象,用来发送电子邮件    
System.Net.Mail.SmtpClient stmp = new SmtpClient(smtElement.Host);
//设置是否需要发送是否需要身份验证,如果不需要下面的credentials是不需要的   
if (smtElement.DefaultCredentials)
{
	stmp.UseDefaultCredentials = true;
	stmp.Credentials = new System.Net.NetworkCredential(smtElement.UserName, smtElement.Password);
}
//发送邮件    
stmp.Send(email);





   

你可能感兴趣的:(String,C#,asp.net,email,NetWork,credentials)