Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mail in C# with the Gmail SMTP server? [duplicate]

Tags:

c#

Possible Duplicate:
Sending email through Gmail SMTP server with C#

For mailing with C# and using the Gmail SMTP server is there any kind of tricky thing that we should do? Because after lot of searching I found some ways for doing this, but I'm getting a failure exception as a result. I guess it's 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 doing this. I really appreciate any help or link to a useful sample. Here's 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);
}
like image 400
Sam Avatar asked Nov 30 '10 12:11

Sam


2 Answers

Try the following code. This is the working code I have been using 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("[email protected]", "YourGmailPassword");

    //Enable SSL.
    mailClient.EnableSsl = true;

    // Create the mail message (from, to, subject, body).
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("[email protected]");
    mailMessage.To.Add(to);

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

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

Reference: Sending Email using a Gmail Account.

like image 59
Zain Shaikh Avatar answered Sep 29 '22 11:09

Zain Shaikh


You should tell the message of the exception. But yes, uncomment that emailClient.EnableSsl = true; If it still not working, your firewall or router is problably blocking the ports.

like image 31
alansiqueira27 Avatar answered Sep 29 '22 12:09

alansiqueira27