通过.NET实现后台自动发送邮件功能的代码,可以将一些基础信息放到web.config文件中进行保存:
Web.config文件信息段:
代码
<
system.net
>
< mailSettings >
< smtp deliveryMethod = " Network " from = " 待发送邮箱地址 " >
< network host = " 待发送邮箱SMTP地址 " userName = " 待发送邮箱地址 " password = " 邮箱密码 " defaultCredentials = " true " />
</ smtp >
</ mailSettings >
</ system.net >
< mailSettings >
< smtp deliveryMethod = " Network " from = " 待发送邮箱地址 " >
< network host = " 待发送邮箱SMTP地址 " userName = " 待发送邮箱地址 " password = " 邮箱密码 " defaultCredentials = " true " />
</ smtp >
</ mailSettings >
</ system.net >
后台实现:
代码
using
System.Net.Mail;
using System.Configuration;
using System.Net.Configuration;
using System.Web.Configuration;
// addresses for send email.
string [] address = new string [] { " 接收邮箱地址1 " , " 接收邮箱地址2 " };
// email body.
string emailBody = " Hello! Guys! " ;
// email subject.
string subject = " This is a test! " ;
// get the config info.
SmtpSection smtpSection = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration( " ~/web.config " )).MailSettings.Smtp;
// save the mail object.
MailMessage mm = new MailMessage();
foreach ( string item in address)
mm.To.Add(item);
mm.From = new MailAddress(smtpSection.From);
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.SubjectEncoding = System.Text.Encoding.UTF8;
mm.IsBodyHtml = true ;
mm.Body = emailBody;
mm.Subject = subject;
// set and send email.
SmtpClient sc = new SmtpClient(smtpSection.Network.Host);
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
sc.Send(mm);
using System.Configuration;
using System.Net.Configuration;
using System.Web.Configuration;
// addresses for send email.
string [] address = new string [] { " 接收邮箱地址1 " , " 接收邮箱地址2 " };
// email body.
string emailBody = " Hello! Guys! " ;
// email subject.
string subject = " This is a test! " ;
// get the config info.
SmtpSection smtpSection = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration( " ~/web.config " )).MailSettings.Smtp;
// save the mail object.
MailMessage mm = new MailMessage();
foreach ( string item in address)
mm.To.Add(item);
mm.From = new MailAddress(smtpSection.From);
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.SubjectEncoding = System.Text.Encoding.UTF8;
mm.IsBodyHtml = true ;
mm.Body = emailBody;
mm.Subject = subject;
// set and send email.
SmtpClient sc = new SmtpClient(smtpSection.Network.Host);
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.Credentials = new System.Net.NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
sc.Send(mm);