2009-07-31 159 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;