电子邮件代码不起作用

时间:2014-01-15 15:36:37

标签: c# asp.net email smtpclient

以下是我发送邮件的代码,它显示错误

  

服务器拒绝了发件人地址。服务器响应为:530 5.7.1需要验证

    System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
    mail.To = "hsbanga@yahoo.com";
    mail.From = "hsbanga@yahoo.com";
    mail.Subject = "Query from agnihotrindt";

    mail.Body = "Name : " + TextBox1.Text + "<br/>" + "Email: " + TextBox2.Text + "<br/>Contact :" + TextBox3.Text + "<br/><br/><b>Address:</b><br/>" + TextBox4.Text + "<br/><b>Comment:</b><br/>" + TextBox5.Text ;
    mail.BodyFormat = System.Web.Mail.MailFormat.Html;

    mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
    mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
    mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
    mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "hsbanga@yahoo.com";
    mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "secret";
    mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "false";

    System.Web.Mail.SmtpMail.SmtpServer = "smtp.mail.yahoo.com";
    System.Web.Mail.SmtpMail.Send(mail);

3 个答案:

答案 0 :(得分:1)

Use

SmtpClient emailClient = new SmtpClient("smtp.mail.yahoo.com");
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("xyz@yahoo.com","*******"); 
emailClient.EnableSsl = true;
emailClient.Credentials = SMTPUserInfo;
emailClient.Port = 465;

MailMessage message = new System.Net.Mail.MailMessage("xyz@gmail.com", "someone@something.something", "fire!!", "Call up 911 and inform my house is on fire and my phone too");
emailClient.Send(message);

答案 1 :(得分:1)

首先,您使用的是什么版本的.NET?如果我没记错的话,System.Web.Mail在.NET 3.5中已被弃用。建议使用System.Net.Mail命名空间。

至于发送带凭据的邮件,我没有C#代码作为示例,因为我将所有邮件配置添加到system.net元素中的web.config。下面是一个如何寻找雅虎的例子。

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network">
      <network host="smtp.mail.yahoo.com" port="465" userName="xyz@yahoo.com" password="*****" enableSsl="true" defaultCredentials="false" />
    </smtp>
  </mailSettings>
</system.net>

这也允许更改邮件配置,而无需在每次密码更改时重新编译应用程序。然后,您可以像这样实例化您的SmtpClient:

var client = new SmtpClient();
client.Send(mailMessage);

答案 2 :(得分:0)

您可以使用:

SmtpClient smtpClient = new SmtpClient("smtp.mail.yahoo.com", 465);
smtpClient.Credentials = new System.Net.NetworkCredential("hsbanga@yahoo.com", "secret");
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage mail = new MailMessage();

smtpClient.Send(mail);