Stormel
Stormel

Reputation: 143

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("[email protected]");
            MailAddress sendTo = new MailAddress("[email protected]");
            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.

Upvotes: 1

Views: 424

Answers (2)

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

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

Upvotes: 1

Hasanka Rathnayake
Hasanka Rathnayake

Reputation: 137

Try this code

        using System.Net.Mail;

        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("[email protected]");
        mail.To.Add("[email protected]");
        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");

Upvotes: 1

Related Questions