There are a few postings around the NET on this, but this one is specifically for C# 2.0, as there are changes to the System.Web and System.Net namespace, as Microsoft moved some classes around and deprecated others.
So... in C# 2.0, this is a code snippet on how to send email via Gmail's smtp service.
You first create your email message, and give it various properties
string fromEmail, toEmail, subject, body;
//set your variables, from, to, subject, etc
System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage();
Msg.SubjectEncoding = Encoding.Default;
Msg.Sender = new MailAddress(fromEmail);
Msg.From = new MailAddress(fromEmail);
Msg.ReplyTo = new MailAddress(fromEmail);
Msg.Priority = MailPriority.Normal;
Msg.IsBodyHtml = false;
Msg.DeliveryNotificationOptions = DeliveryNotificationOptions.None;
Msg.BodyEncoding = Encoding.Default;
Msg.To.Add(toEmail);
Msg.Subject = subject;
Msg.Body = body;
You then create an instance of the SMTP client, make sure ssl is enabled, and that the port used is either 587 or 465 (587 worked for me). And make sure you pass your gmail email and password as the network credentials.
string login, password, smtpServer;
//set your server, login, and password...
smtpServer = "smtp.gmail.com";
login = "youremail@gmail.com";
password = "yourpassword";
//create the SmtpClient,
//don't use the System.Web namespace
System.Net.Mail.SmtpClient smtpClient = new SmtpClient(smtpServer);
smtpClient.Port = 587;//or 465
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential(login, password);
smtpClient.Timeout = 6000;
smtpClient.Send(Msg);
Google's SMTP Reference
Voila!
No comments:
Post a Comment