4

我是 C# 新手,我正在尝试从我正在开发的桌面程序发送电子邮件。这是我正在使用的代码,但我不断收到以下错误:

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("thesma@gmail.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("ideas@gmail.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com",578);
smtp.EnableSsl = true;
smtp.Send(message);

我似乎无法找出问题所在...

4

4 回答 4

8

您需要为 Gmail 设置凭据

var client = new SmtpClient("smtp.gmail.com", 587)
 {
    Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
    EnableSsl = true
};
client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
于 2013-07-22T12:41:05.530 回答
3

最有可能缺少凭据:

smtp.Credentials = new System.Net.NetworkCredential("ideas@gmail.com", "password");

所以:

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential("ideas@gmail.com", "Password");
smtp.EnableSsl = true;
smtp.Send(message);

或者,您可以将(几乎所有)这些东西存储在 中app.config,但我不确定您需要它有多安全,因为打开应用程序目录(和该文件)的任何用户都可以清楚地看到用户/密码。为了完成:

<system.net>
  <mailSettings>
    <smtp from="ideas@gmail.com">
      <network host="smtp.gmail.com"
               enableSsl="true"
               userName="ideas@gmail.com"
               password="password"
               port="587" />
    </smtp>
  </mailSettings>
</system.net>
于 2013-07-22T12:42:15.907 回答
1

网络凭据非常重要,但有时我们需要检查端口587是否被阻塞。

   SmtpClient client = new SmtpClient();
    client.Credentials = new System.Net.NetworkCredential("jorgesys@gmail.com", "whocaresdupe");
    client.Port = 587;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    try
    {
        client.Send(mail);          
    } catch (Exception ex)
    {
       Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendEmail.aspx';}</script>");
    }
于 2015-08-29T01:49:19.733 回答
0

我的公司使用 McAfee 中的设置阻止台式机/笔记本电脑发送电子邮件。检查 Windows 事件视图以查看是否存在电子邮件被阻止的条目。

于 2016-03-18T13:20:26.940 回答