2013-07-22 257 views
1

我是C#的新手,我试图从我正在开发的桌面程序发送电子邮件。下面是我使用的代码,但我不断收到以下错误:无法连接到远程服务器

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); 
message.To.Add("[email protected]"); 
message.Subject = "This is the Subject line"; 
message.From = new System.Net.Mail.MailAddress("[email protected]"); 
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); 

我似乎无法找出问题是什么...

+1

有什么异常?或者是什么问题? – wudzik

回答

2

缺少凭据最有可能的:

smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password"); 

所以:

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); 
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "Password"); 
smtp.EnableSsl = true; 
smtp.Send(message); 

或者,你可以存储(几乎所有)这个东西在app.config,虽然我不知道你如何安全的需要它,因为用户名/密码将是打开的应用程序的任何用户清晰可见目录(和那个文件)。对于完成的缘故:

<system.net> 
    <mailSettings> 
    <smtp from="[email protected]"> 
     <network host="smtp.gmail.com" 
       enableSsl="true" 
       userName="[email protected]" 
       password="password" 
       port="587" /> 
    </smtp> 
    </mailSettings> 
</system.net> 
1

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

SmtpClient client = new SmtpClient(); 
    client.Credentials = new System.Net.NetworkCredential("[email protected]", "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>"); 
    } 
+1

这是如何直接检查端口是否打开? – Pythoner1234

0

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

相关问题