2009-01-16 171 views
41

我需要通過我的C#應用​​程序發送電子郵件。使用C發送電子郵件#

我來自VB 6的背景,並有很多與MAPI控制不好的經驗。 首先,MAPI不支持HTML電子郵件,其次,所有電子郵件都發送到我的默認郵件發件箱。所以我仍然需要點擊發送接收。

如果我需要發送批量html html格式的電子郵件(100-200),那麼在C#中這樣做的最好方法是什麼?

在此先感謝。

回答

65

您可以使用System.Net.Mail.MailMessage類的.NET Framework。

你可以找到MSDN documentation here

下面是一個簡單的例子(代碼片段):

using System.Net; 
using System.Net.Mail; 
using System.Net.Mime; 

... 
try 
{ 

    SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net"); 

    // set smtp-client with basicAuthentication 
    mySmtpClient.UseDefaultCredentials = false; 
    System.Net.NetworkCredential basicAuthenticationInfo = new 
     System.Net.NetworkCredential("username", "password"); 
    mySmtpClient.Credentials = basicAuthenticationInfo; 

    // add from,to mailaddresses 
    MailAddress from = new MailAddress("[email protected]", "TestFromName"); 
    MailAddress to = new MailAddress("[email protected]", "TestToName"); 
    MailMessage myMail = new System.Net.Mail.MailMessage(from, to); 

    // add ReplyTo 
    MailAddress replyto = new MailAddress("[email protected]"); 
    myMail.ReplyToList.Add(replyTo); 

    // set subject and encoding 
    myMail.Subject = "Test message"; 
    myMail.SubjectEncoding = System.Text.Encoding.UTF8; 

    // set body-message and encoding 
    myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>."; 
    myMail.BodyEncoding = System.Text.Encoding.UTF8; 
    // text or html 
    myMail.IsBodyHtml = true; 

    mySmtpClient.Send(myMail); 
} 

catch (SmtpException ex) 
{ 
    throw new ApplicationException 
    ("SmtpException has occured: " + ex.Message); 
} 
catch (Exception ex) 
{ 
    throw ex; 
} 
+1

還有什麼替代方法將密碼直接嵌入到代碼中? – 2009-06-15 23:58:30

+4

NetworkCredential類過載。如果你提供了一個空的構造函數,它將用當前用戶創建實例。或者,您也可以加密用戶名和密碼並將其存儲在外部。這也取決於你如何設置你的郵件服務器。您可以在本地主機上設置SMTP服務器,並允許它成爲回送地址的中繼,以便您可以發送沒有憑證的電子郵件。我們做後者。它輕巧,簡單,並且不需要存儲密碼(因爲任何人都可以從回送地址進行中繼 - 這意味着IIS也可以)。 – 2009-11-06 12:13:39

4

.NET框架有一些內置類,允許您通過應用程序發送電子郵件。

您應該看看System.Net.Mail命名空間,您將在其中找到MailMessage和SmtpClient類。 您可以將MailMessage類的BodyFormat設置爲MailFormat.Html。

如果您使用MailMessage類的AlternateViews屬性,那麼您可以提供純文本版本的郵件,以便它可以被不支持HTML的客戶端讀取。

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

+0

打我吧:) :) – 2009-01-16 09:02:03

+0

如何被定義的答案的順序?前一段時間splattne的答案是3號之一,現在它的第一個... 覺得我應該閱讀常見問題解答;)(第一次在這裏) – 2009-01-16 09:08:07

+0

首先接受的答案,低於票 – edosoft 2009-01-16 10:29:44

1

使用的命名空間System.Net.Mail。 Here is a link to the MSDN page

您可以使用SmtpClient類發送電子郵件。

我解釋了代碼示例,因此請檢查MSDN以瞭解詳細信息。

MailMessage message = new MailMessage(
    "[email protected]", 
    "[email protected]", 
    "Subject goes here", 
    "Body goes here"); 

SmtpClient client = new SmtpClient(server); 
client.Send(message); 

發送很多電子郵件的最佳方式是將這樣的東西放在forloop併發送!

6

代碼:

using System.Net.Mail 

new SmtpClient("smtp.server.com", 25).send("[email protected]", 
              "[email protected]", 
              "subject", 
              "body"); 

大量電子郵件:

SMTP服務器通常會對連接帽的數量限制可以處理一次,如果你嘗試發送數百封電子郵件的你應用程序可能顯示無響應。

解決方案:

  • 如果你正在建設一個WinForm然後用一個BackgroundWorker來處理隊列。
  • 如果您使用IIS SMTP服務器或具有發件箱文件夾的SMTP服務器,則可以使用SmtpClient()。PickupDirectoryLocation =「c:/ smtp/outboxFolder」;這將保持您的系統響應。
  • 如果不使用本地SMTP服務器比你可以建立一個系統服務使用Filewatcher監控forlder則比會處理你在裏面刪除任何郵件。
2

我強烈建議aspNetEmail庫:http://www.aspnetemail.com/

System.Net.Mail會得到你的地方,如果你的需求是隻有基本的,但如果你遇到麻煩,請查看aspNetEmail。它爲我節省了一大堆時間,而且我知道其他發誓的人也會發誓!

15

的最佳方式發送大量的電子郵件,以獲取更多更快的方法是使用threads.I已經寫了羣發emails.I已通過創建兩個線程池分隔的批量電子郵件ID爲兩批這個控制檯應用程序。

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
using System.Net.Mail; 

namespace ConsoleApplication1 
{ 
    public class SendMail 
    { 
     string[] NameArray = new string[10] { "Recipient 1", 
               "Recipient 2", 
               "Recipient 3", 
               "Recipient 4", 
               "Recipient 5", 
               "Recipient 6", 
               "Recipient 7", 
               "Recipient 8", 
               "Recipient 9", 
               "Recipient 10" 
              };   

     public SendMail(int i, ManualResetEvent doneEvent) 
     { 
      Console.WriteLine("Started sending mail process for {0} - ", NameArray[i].ToString() + " at " + System.DateTime.Now.ToString()); 
      Console.WriteLine(""); 
      SmtpClient mailClient = new SmtpClient(); 
      mailClient.Host = Your host name; 
      mailClient.UseDefaultCredentials = true; 
      mailClient.Port = Your mail server port number; // try with default port no.25 

      MailMessage mailMessage = new MailMessage(FromAddress,ToAddress);//replace the address value 
      mailMessage.Subject = "Testing Bulk mail application"; 
      mailMessage.Body = NameArray[i].ToString(); 
      mailMessage.IsBodyHtml = true; 
      mailClient.Send(mailMessage); 
      Console.WriteLine("Mail Sent succesfully for {0} - ",NameArray[i].ToString() + " at " + System.DateTime.Now.ToString()); 
      Console.WriteLine(""); 

      _doneEvent = doneEvent; 
     } 

     public void ThreadPoolCallback(Object threadContext) 
     { 
      int threadIndex = (int)threadContext; 
      Console.WriteLine("Thread process completed for {0} ...",threadIndex.ToString() + "at" + System.DateTime.Now.ToString()); 
      _doneEvent.Set(); 
     }  

     private ManualResetEvent _doneEvent; 
    } 


    public class Program 
    { 
     static int TotalMailCount, Mailcount, AddCount, Counter, i, AssignI; 
     static void Main(string[] args) 
     { 
      TotalMailCount = 10; 
      Mailcount = TotalMailCount/2; 
      AddCount = Mailcount; 
      InitiateThreads();      

      Thread.Sleep(100000); 
     } 

     static void InitiateThreads() 
     { 
      //One event is used for sending mails for each person email id as batch 
      ManualResetEvent[] doneEvents = new ManualResetEvent[Mailcount]; 

      // Configure and launch threads using ThreadPool: 
      Console.WriteLine("Launching thread Pool tasks..."); 

      for (i = AssignI; i < Mailcount; i++)    
      { 
       doneEvents[i] = new ManualResetEvent(false); 
       SendMail SRM_mail = new SendMail(i, doneEvents[i]); 
       ThreadPool.QueueUserWorkItem(SRM_mail.ThreadPoolCallback, i); 
      } 

      Thread.Sleep(10000); 

      // Wait for all threads in pool to calculation... 
      //try 
      //{ 
      // // WaitHandle.WaitAll(doneEvents); 
      //} 
      //catch(Exception e) 
      //{ 
      // Console.WriteLine(e.ToString()); 
      //} 

      Console.WriteLine("All mails are sent in this thread pool."); 
      Counter = Counter+1; 
      Console.WriteLine("Please wait while we check for the next thread pool queue"); 
      Thread.Sleep(5000); 
      CheckBatchMailProcess();    
     } 

     static void CheckBatchMailProcess() 
     { 

      if (Counter < 2) 
      { 
       Mailcount = Mailcount + AddCount; 
       AssignI = Mailcount - AddCount; 
       Console.WriteLine("Starting the Next thread Pool"); 

       Thread.Sleep(5000); 
       InitiateThreads(); 
      } 

      else 
      { 
       Console.WriteLine("No thread pools to start - exiting the batch mail application"); 
       Thread.Sleep(1000); 
       Environment.Exit(0); 
      } 
     } 
    } 
} 

我在一個sample.It數組列表定義了10名,收件人創建電子郵件的兩批創建兩個線程池發送mails.You可以選擇從您的數據庫也細節。

您可以通過複製並在控制檯應用程序粘貼使用此代碼。(更換Program.cs文件)。然後該應用程序就可以使用了。

我希望這可以幫助您:)。

3

可以使用SMTP使用SMTP或CDO

發送電子郵件:

mail.From = new MailAddress("[email protected]"); 
mail.To.Add("to_address"); 
mail.Subject = "Test Mail"; 
mail.Body = "This is for testing SMTP mail from GMAIL"; 

SmtpServer.Port = 587; 
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password"); 
SmtpServer.EnableSsl = true; 

來源:C# SMTP Email

CDO.Message oMsg = new CDO.Message(); 
CDO.IConfiguration iConfg; 
iConfg = oMsg.Configuration; 
ADODB.Fields oFields; 
oFields = iConfg.Fields; 
ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"]; 
oFields.Update(); 
oMsg.Subject = "Test CDO"; 
oMsg.From = "from_address"; 
oMsg.To = "to_address"; 
oMsg.TextBody = "CDO Mail test"; 
oMsg.Send(); 

來源:C# CDO Email

曼利

0

查看FluentEmail庫。 我的博客上講述它here

您有您的需要一個很好的流暢API:

Email.FromDefault() 
.To("[email protected]") 
.Subject("New order has arrived!") 
.Body("The order details are…") 
.Send();