试图用C#发送邮件,但它似乎没有工作

问题描述:

所以我想尝试使用Visual C#应用程序发送自己的一些邮件,但它似乎只是通过代码运行(我知道这是因为我把代码末尾的消息框)并且不发送任何内容。我确实更改了以下电子邮件信息,原因很明显。试图用C#发送邮件,但它似乎没有工作

这是我有:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net.Mail; 
using System.Net; 

namespace WindowsFormsApplication9 
{ 
    public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string Host = "smtp.live.com"; 
     Int16 Port = 587; 
     bool SSL = true; 
     string Username = "[email protected]"; 
     string Password = "mypassword"; 

     // Mail options 
     string To = "[email protected]"; 
     string From = "[email protected]"; 
     string Subject = "This is a test"; 
     string Body = "It works!"; 

     MailMessage mm = new MailMessage(From, To, Subject, Body); 
     SmtpClient sc = new SmtpClient(Host, Port); 
     NetworkCredential netCred = new NetworkCredential(Username, Password); 
     sc.EnableSsl = SSL; 
     sc.UseDefaultCredentials = false; 
     sc.Credentials = netCred; 

     MessageBox.Show("Test"); 
    } 
} 
} 

*注意,我从中得到任何错误。

+3

提示:您设置的所有信息(主机,从,到,主题,正文),设置凭据,以及所有看起来很好。你究竟在哪里发送邮件? (另一个提示:在'sc.Credentials = netCred;'和'MessageBox.Show(“Test”);'之间应该有更多的了解) – 2012-04-14 02:33:43

+1

刚刚意识到我忘了实际发送消息。现在解决这个问题。 – Hexo 2012-04-14 02:37:28

+0

很好。你开始了吗?现在我可以为你回来的时候发表一个答案。 :) – 2012-04-14 02:47:19

你实际上并没有发送邮件。

添加到您的代码 - 你应该能够找出其中:

sc.Credentials = netCred; 

try 
{ 
    sc.Send(message); 
} 
catch (Exception ex) 
{ 
    MessageBox(ex.ToString());    
}    
MessageBox.Show("Test"); 
+0

+1,但要匹配OP的例子,它应该是'sc.Send(message);' – Robbie 2012-04-14 02:44:38

+0

好的结果。固定。 – 2012-04-14 02:45:58

+0

谢谢,非常感谢帮助(我得到它的工作,呜呼。现在执行附件:D) 我不知道为什么我试图stmpclient,但。 – Hexo 2012-04-14 03:00:35

添加这些命名空间...

using System.Net.Mail; 
using System.Net; 
using System.Configuration; 

添加以下代码行的代码隐藏文件您想在哪里发送电子邮件。

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("yourEmailId", "destinationEmailId"); 
mail.Subject = ""; //Enter the text for the subject of the mail in quotes. 
mail.Body = ""; //Enter the text for the body of mail within the quotes. 
mail.IsBodyHtml = true; 
SmtpClient client = new SmtpClient("smtp.live.com"); 
NetworkCredential cred = new NetworkCredential("yourEmailId", "yourPassword"); 
client.EnableSsl = true; 
client.Credentials = cred; 
try 
{ 
client.Send(mail); 
} 
catch (Exception) 
{ 
} 
+0

这不是很可读 – Robbie 2012-04-14 02:43:35

+1

这里有很多噪音是没有必要的。除了一行代码外,OP还提供了所有相关的信息(如果你省略'try..catch'),这很难阅读,因为额外的噪声使得实际的解决方案很难找到。 – 2012-04-14 02:45:12