简体   繁体   中英

C# Send E-Mail issue

I'm trying to send an e-mail in C#,and I'm having some issues.Whenever I try to send an e-mail,I get a message "Error: Failure to send mail". Here is my code:

    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);
        }

Also I have this declaration:

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

Hope you can help me.

Try this code

        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");

you can try this and make sure you are using valid login credential and you have internet connection:

 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)
  {               
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM