How to send mail to C # using a Gmail SMTP server?

Possible duplicate:
Sending email through a Gmail SMTP server using C #

For mailing from C # and using the Gmail SMTP server, is there any complicated thing that we have to do? Because after many searches, I found several ways to do this, but as a result I get a crash exception. I suppose because I don't handle TSL for Gmail (because it works with TSL), but I don't know how to handle TSL with C # for this. I really appreciate any help or link to a useful sample. Here is my code:

public string SendMail(string senderMail, string receiverMail, string attachmentPath)
{
  var fromMailAddress = new MailAddress(senderMail);
  var toMailAddress = new MailAddress(receiverMail);

  MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress);
  mailMessage.Subject = "My Subject";
  mailMessage.Body = "This is the body of this message for testing purposes";

  Attachment attachFile = new Attachment(attachmentPath);
  mailMessage.Attachments.Add(attachFile);

  SmtpClient emailClient = new SmtpClient();

  NetworkCredential credential = new NetworkCredential();
  credential.UserName = fromMailAddress.User;
  credential.Password = "password";

  emailClient.Credentials = credential;
  emailClient.Port = 587;
  emailClient.Host = "smtp.gmail.com";

  //emailClient.EnableSsl = true; //Here should be for TSL, but how?

  emailClient.Send(mailMessage);
}
+5
source share
2 answers

Try using the following code. This is the working code that I have used for a long time.

    // Configure mail client (may need additional
    // code for authenticated SMTP servers).
    SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

    // Set the network credentials.
    mailClient.Credentials = new NetworkCredential("YourGmailEmail@gmail.com", "YourGmailPassword");

    //Enable SSL.
    mailClient.EnableSsl = true;

    // Create the mail message (from, to, subject, body).
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("zain.you2@gmail.com");
    mailMessage.To.Add(to);

    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = isBodyHtml;
    mailMessage.Priority = mailPriority;

    // Send the mail.
    mailClient.Send(mailMessage);

: Gmail.

+5

. , , emailClient.EnableSsl = true; , , , .

+1

All Articles