SSL SMTP with .NET Framework
Sending emails through an SSL SMTP server using the .NET Framework can be achieved by configuring the SMTP client accordingly. Here's a step-by-step guide:
1. Create an SmtpClient Instance:
System.Net.Mail.SmtpClient _SmtpServer = new System.Net.Mail.SmtpClient();
2. Specify Server Host and Port:
_SmtpServer.Host = "smtp.yourserver.com"; _SmtpServer.Port = 465;
3. Enable SSL:
_SmtpServer.EnableSsl = true;
4. Set Credentials (Optional):
_SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
5. Configure Send Timout:
_SmtpServer.Timeout = 5000;
6. Set UseDefaultCredentials to False:
_SmtpServer.UseDefaultCredentials = false;
7. Create a MailMessage:
MailMessage mail = new MailMessage(); mail.From = new MailAddress(from); mail.To.Add(to); mail.Subject = subject; mail.Body = content; mail.IsBodyHtml = useHtml;
8. Send the Email:
_SmtpServer.Send(mail);
Example with Gmail's SMTP Server:
using System.Web.Mail; using System; public class MailSender { public static bool SendEmail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, MailFormat pFormat) { try { MailMessage myMail = new MailMessage(); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com"); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465"); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2"); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword); myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); myMail.From = pGmailEmail; myMail.To = pTo; myMail.Subject = pSubject; myMail.BodyFormat = pFormat; myMail.Body = pBody; SmtpMail.SmtpServer = "smtp.gmail.com:465"; SmtpMail.Send(myMail); return true; } catch (Exception ex) { throw; } } }
The above is the detailed content of How to Configure SSL SMTP Email Sending with the .NET Framework?. For more information, please follow other related articles on the PHP Chinese website!