天天看點

通過.NET實作背景自動發送Email功能的代碼示例

通過.NET實作背景自動發送郵件功能的代碼,可以将一些基礎資訊放到web.config檔案中進行儲存:

Web.config檔案資訊段:

<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);

繼續閱讀