萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> C# EmailHelper.cs 郵件發送模塊代碼

C# EmailHelper.cs 郵件發送模塊代碼

  一個C#發郵件模塊,EmailHelper.cs 代碼,是從一個C#工具包中拷貝出來的,在ASP.NET或C#項目中添加發送郵件功能時,這個類挺方便,使用時指定郵件標題、郵件正文、收件人、是否為HTML格式等參數即可,代碼如下:

  01using System;

  02using System.Collections.Generic;

  03using System.Linq;

  04using System.Text;

  05namespace CLB.Utility.Tools

  06{

  07 public class EmailHelper

  08 {

  09 ///<summary>

  10 /// 發送郵件

  11 ///<summary>

  12 ///<param name="subject"> 郵件標題</param>

  13 /// <param name="body">郵件正文</param>

  14 /// <param name="to">收件人</param>

  15 /// <param name="Ishtml">是否為html格式</param>

  16 public static bool sendmail(string subject, string body, string to, bool Ishtml)

  17 {

  18 using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage())

  19 {

  20 msg.To.Add(to);

  21 msg.From = new System.Net.Mail.MailAddress("郵箱地址", "標題", System.Text.Encoding.UTF8);

  22 msg.Subject = subject;//郵件標題

  23 msg.SubjectEncoding = System.Text.Encoding.UTF8;//郵件標題編碼

  24 msg.Body = body;//郵件內容

  25 msg.BodyEncoding = System.Text.Encoding.UTF8;//郵件內容編碼

  26 msg.IsBodyHtml = Ishtml;//是否是HTML郵件

  27 msg.Priority = System.Net.Mail.MailPriority.High;//郵件優先級

  28 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();

  29 client.Credentials = new System.Net.NetworkCredential("郵箱地址", "密碼");

  30 client.Host = "域名";

  31 object userState = msg;

  32 try

  33 {

  34 client.Send(msg);

  35 return true;

  36 }

  37 catch

  38 {

  39 return false;

  40 }

  41 }

  42 }

  43 }

  44}

copyright © 萬盛學電腦網 all rights reserved