如何从c#发送邮件

我有代码,

System.Web.Mail.MailMessage oMailMessage = new MailMessage(); oMailMessage.From = strFromEmaild; oMailMessage.To = strToEmailId; oMailMessage.Subject = strSubject; oMailMessage.Body = strBody; SmtpMail.SmtpServer = "localhost"; SmtpMail.Send(oMailMessage); 

(所有变量都有值)

我已经安装了SMTP虚拟服务。 为什么它无法发送电子邮件。 为什么不工作?

编辑

 public bool SendMail(string strToEmailId, string strFromEmaild, string strSubject, string strBody) { try { System.Web.Mail.MailMessage oMailMessage = new MailMessage(); oMailMessage.From = strFromEmaild; oMailMessage.To = strToEmailId; oMailMessage.Subject = strSubject; oMailMessage.Body = strBody; SmtpMail.SmtpServer = "SERVERNAME"; SmtpMail.Send(oMailMessage); return true; } catch (Exception ex) { return false; } } 

我有这个代码。 它正在执行正常并返回true,但我没有在收件箱中收到任何电子邮件。

还有什么可能是错的?

在C:\ Inetpub \ mailroot \ Badmail的BadMail Dir中获取一些邮件也在队列目录中获取一些邮件……这意味着什么.. ??

我发现邮件只能发送到Gmail帐户……为什么会这样?

确定错误是什么:

 try { SmtpMail.Send(oMailMessage); } catch (Exception ex) { //breakpoint here to determine what the error is: Console.WriteLine(ex.Message); } 

从这里开始,请使用该exception详细信息编辑您的问题。

正如其他人所提到的,您的代码很好,很可能是您的SMTP配置中的某些内容,或者您​​发送测试电子邮件的电子邮件客户端将其标记为垃圾邮件。 如果它是垃圾邮件,那很容易弄清楚。 如果它与电子邮件有关,您可以转到您的mailroot文件夹,它们将是一些文件夹,其中包含电子邮件文件以及说明。 查看BadMail文件夹或队列文件夹中是否有任何内容,并在记事本中打开它们,并查看为什么没有发送它们的错误。

很难说,但有一种可能性是您没有在SMTP虚拟服务器上启用匿名访问。 转到虚拟服务器属性对话框,选择“访问”选项卡,单击“访问控制”按钮,并确保已启用“匿名访问”。

您的程序似乎没有任何function上的错误。 这可能是您的程序和邮件服务器之间的配置问题。 我会尝试以下方法来诊断问题。

  1. 将代码包装在try / catch块中,查看exception消息是否包含有用数据
  2. 使用127.0.0.1而不是localhost只是为了排除任何疯狂的事情
  3. 确保您的SMTP服务器在标准端口上运行(我相信25)

您好,您可以按照以下代码:

 try { SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.EnableSsl = true; client.Timeout = 100000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("your gmail id", "password"); MailMessage msg = new MailMessage(); msg.To.Add(textBoxTo.Text); msg.From = new MailAddress("your gmail id"); msg.Subject = textBoxSubject.Text; msg.Body = textBoxMsg.Text; Attachment data = new Attachment(textBoxAttachment.Text); msg.Attachments.Add(data); client.Send(msg); MessageBox.Show("Successfully Sent Message."); } catch (Exception ex) { MessageBox.Show(ex.Message); } 

你试过127.0.0.1而不是Localhost吗? 您还测试了SMTP服务是否正常工作,请查看此链接以获取详细信息。

在虚拟smtp服务器中添加中继限制和连接控制,以便不允许任何外部连接

在此处输入图像描述