2009-07-31 155 views
0

我有下面的代碼,但我得到一個例外,一個smtp主機沒有定義。如果我正在使用Visual Studio在本地計算機上運行並進行測試,那麼我需要做些什麼才能夠從我的計算機發送電子郵件。我必須打開一些Windows服務嗎?使用.NET發送電子郵件

private void SendMailToAdminToApprove(string email_, string name_) 
{ 
    MailMessage msg = new MailMessage(); 
    msg.From = new MailAddress("[email protected]", "Person's Name"); 
    msg.To.Add(new MailAddress("[email protected]", "Adam")); 
    msg.Subject = "Message Subject"; 
    msg.Body  = "Mail body content"; 
    msg.IsBodyHtml = true; 
    msg.Priority = MailPriority.High; 
    try 
    { 
     SmtpClient c = new SmtpClient(); 
     c.Send(msg); 
    } 
    catch (Exception ex) 
    { 
     Console.Write("T"); 
    } 
} 
+0

請確保在完成後處置MailMessage。 – 2009-07-31 16:42:54

回答

8

您需要將SMTP主機設置爲指向實際的SMTP服務器。一種選擇是在自己的機器上運行SMTP服務,但也可以指向ISP的服務器。

編輯

由於pcampbell和Skeolan提到的,實際價值應該進入的app.config。我不確定本地主機是否會成爲例外:這取決於您是否希望不運行本地服務器。

7

你需要指定SMTP主機的位置:

string smtpHost = "localhost"; 
//or go to your config file 
smtpHost = ConfigurationManager.AppSettings["MySmtpHost"].ToString(); 

SmtpClient c = new SmtpClient(smtpHost); 
+4

更好,然後將實際的stmpHost字符串提取到app.config或web.config中,以便您可以針對不同的部署進行修改。然後,您可以使用「localhost」進行開發(假設您正在本地計算機上運行[虛擬?] smtp服務),但仍可以選擇稍後指定外部電子郵件服務器,而無需重新編譯。 – Skeolan 2009-07-31 16:51:28

1

您需要定義SMTP中繼:

SmtpClient c = new SmtpClient("relay.yourdomain.com"); 

或者,如果你在本地運行繼電器:

SmtpClient c = new SmtpClient("localhost"); 
1

您應該更改此部分:

SmtpClient c = new SmtpClient(); 
// Either specify a SMTP server above, or set c.Host 
c.Send(msg); 

您需要指定將使用哪個SMTP服務器發送此消息。如果您在本地安裝SMTP服務器,則可能是本地主機 - 但除此之外,您需要設置適當的外發郵件服務器。

0

以下是我用於使用C#發送電子郵件的代碼。如果你需要的話,我還將代碼發送給本地文件。

 SmtpClient smtp = new SmtpClient(smtpServer, portNumber); 
     // Disable SSL when saving to directory. 
     smtp.EnableSsl = true; 
     smtp.Credentials = new NetworkCredential(mailFrom, password); 

     // Set mail to be delivered to a folder 
     //smtp.PickupDirectoryLocation = @"C:\mail\Send"; 
     //smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;