1

我正在尝试用 C# 发送电子邮件,但遇到了一些问题。每当我尝试发送电子邮件时,都会收到一条消息“错误:发送邮件失败”。这是我的代码:

    try
        {
            client.Host = "smtp.gmail.com";
            client.Port = 465;
            client.UseDefaultCredentials = false;
            client.Credentials = smtpCreds;
            client.EnableSsl = true;

            MailAddress sendFrom = new MailAddress("from@domain.com");
            MailAddress sendTo = new MailAddress("to@domain.com");
            MailMessage msg = new MailMessage(sendFrom,sendTo);
            msg.Subject = "Subject";
            msg.Body = "Body";
            client.Send(msg);
        }
        catch (Exception e)
        {
            MessageBox.Show("Error:" + e.Message);
        }

我也有这个声明:

    public SmtpClient client = new SmtpClient();
    public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password");

希望您能够帮助我。

4

2 回答 2

1

试试这个代码

        using System.Net.Mail;

        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("sender@gmail.com");
        mail.To.Add("reciever@gmail.com");
        mail.Subject = ("e mail subject");
       mail.Body = ("message body");
        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential("sender's username",            "sender's password");
        SmtpServer.EnableSsl = true;
        SmtpServer.Send(mail);
        MessageBox.Show("mail Send");
于 2013-04-13T09:37:50.347 回答
1

你可以试试这个,并确保你使用的是有效的登录凭据并且你有互联网连接:

 MailMessage mail = new MailMessage();
 mail.Subject = "Your Subject";
 mail.From = new MailAddress("senderMailAddress");
 mail.To.Add("ReceiverMailAddress");
 mail.Body = "Hello! your mail content goes here...";
 mail.IsBodyHtml = true;

 SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
 smtp.EnableSsl = true;
 NetworkCredential netCre = new NetworkCredential("SenderMailAddress","SenderPassword" );
 smtp.Credentials = netCre;

 try
  {
   smtp.Send(mail);                
  }
  catch (Exception ex)
  {               
  }
于 2013-04-13T09:53:15.327 回答