天天看點

談談System.Net.Mail和System.Web.Mail

System.Net.Mail是作為System.Web.Mail的替代來發送EMAIL.

System.Net.Mail

Code

 1private void SendMailByNet(){

 2        MailMessage objMailMessage = new MailMessage();

 3

 4        objMailMessage.From=new MailAddress("UserFromMail");

 5        objMailMessage.To.Add(new MailAddress("UserToMail"));

 6        objMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

 7        objMailMessage.Subject = "This is test";

 8        objMailMessage.Body = "Hi,Pippo<br/><br/> This is testing Email.";

 9        objMailMessage.IsBodyHtml = true;

10

11        SmtpClient objSmtpClient = new SmtpClient();

12        objSmtpClient.Host = "SMTP";

13        objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

14        objSmtpClient.Credentials = new System.Net.NetworkCredential("UserFromMail","PWD");

15        //objSmtpClient.EnableSsl = true;//SMTP 伺服器要求安全連接配接需要設定此屬性

16

17        try

18        {

19            objSmtpClient.Send(objMailMessage);

20        }

21        catch (Exception ex)

22        {

23            Response.Write(ex.Message);

24        }

25}

System.Web.Mail

Code

 1private void SendMailByWeb()

 2{

 3        MailMessage objMailMessage = new MailMessage();

 4

 5        SmtpMail.SmtpServer = System.Configuration.ConfigurationManager.AppSettings["SMTP"];

 6

 7        objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");

 8        objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", System.Configuration.ConfigurationManager.AppSettings["FROM"]);

 9        //objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", System.Configuration.ConfigurationManager.AppSettings["PWD"]);//密碼可以不提供

10        objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");//SMTP 伺服器要求安全連接配接需要設定此屬性

11

12        objMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

13        objMailMessage.From = System.Configuration.ConfigurationManager.AppSettings["FROM"];

14        objMailMessage.To = "UserToMail";

15        objMailMessage.Subject = "this is test";

16        objMailMessage.Body = "Hi Pippo,<br/>This is testing EMAIL.";

17        objMailMessage.BodyFormat = MailFormat.Html;

18

19        try

20        {

21            SmtpMail.Send(objMailMessage);

22        }

23        catch (Exception ex)

24        {

25            Response.Write(ex.Message);

26        }

27}

繼續閱讀