2016-04-25 75 views
0

enter image description here我想学习如何发送一个简单的电子邮件与c#visual studio窗体应用程序。 (它也可以是我关心的所有控制台应用程序)。下面是我的代码(我看不出有什么不对的代码,它应该工作吧?):从窗体应用程序发送电子邮件(为什么不工作)

using System.Net.Mail; 
namespace WindowsFormsApplication1 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      MailMessage mail = new MailMessage(); 
      SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 

      mail.From = new MailAddress("(here is my email)"); 
      mail.To.Add("(here is my email)"); 
      mail.Subject = "toja"; 
      mail.Body = "ja"; 

      SmtpServer.Port = 587; 
      SmtpServer.Credentials = new System.Net.NetworkCredential("(here is my email)", "(here is my password)"); 
      SmtpServer.EnableSsl = true; 

      SmtpServer.Send(mail); 
      MessageBox.Show("mail Send"); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 

} 

}

+0

你怎么知道它不起作用?什么是错误? – randominstanceOfLivingThing

+0

我不能告诉你整个eror的原因,我不能复制它,但这里是开始的几行:“System.Net.Mail.SmtpException:SMTP服务器rewuires一个安全的连接或客户端没有authuenticated。服务器响应是:5.5.1身份验证“ –

+0

从此[页面](https://support.google.com/mail/answer/78775?hl=zh-CN),如果您尝试在端口465上配置SMTP服务器(使用SSL/TLS)和587端口(使用STARTTLS),但仍然无法发送邮件,请尝试配置SMTP以使用端口25(使用SSL/TLS)。 – randominstanceOfLivingThing

回答

0

我用下面的从C#窗体应用程序并将其发送电子邮件作品。 也许你应该尝试添加smtp.UseDefaultCredentials = false属性并设置凭证属性?

// Create our new mail message 
MailMessage mailMessage = new MailMessage(); 
mailMessage.To.Add("toAddress"); 
mailMessage.From = new MailAddress("fromAddress"); 
mailMessage.Subject = "subject"; 
mailMessage.Body = "body"; 

// Set the IsBodyHTML option if it is HTML email 
mailMessage.IsBodyHtml = true; 

// Enter SMTP client information 
SmtpClient smtpClient = new SmtpClient("mail.server.address"); 
NetworkCredential basicCredential = new NetworkCredential("username", "password"); 
smtpClient.UseDefaultCredentials = false; 
smtpClient.Credentials = basicCredential; 
smtpClient.Send(mailMessage); 

如果使用Gmail,您可以在这里找到SMTP服务器信息https://support.google.com/a/answer/176600?hl=en。它看起来像地址是smtp.gmail.com,而端口是465(对于SSL)或587(对于TLS)。我建议你先尝试使用默认端口25,确保你的电子邮件通过,然后根据需要调整到不同的端口。

+0

我试过使用您的代码和“NetworkCredentials “在这一行中:NetworkCredential basicCredential = new NetworkCredential(”username“,”password“);是一个错误,我该怎么做呢?我觉得我错过了很多东西,这真是让我非常困扰。 –

+0

你可能需要以下导入...使用System.Security.Cryptography;使用System.Net的 ;使用System.Net.Mail的 ;使用System.Net.Mime的 ;使用System.Net.Mime的 – Phil

+0

当我点击一个错误apers按钮。我认为这与港口有关。我应该使用什么端口? –

相关问题