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);
}
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("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);
Reference: Sending Email using a Gmail Account.
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.
精彩评论