C#发送电子邮件问题

时间:2013-04-13 08:46:15

标签: c# email send

我正在尝试用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");

希望你能帮助我。

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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)
  {               
  }