程序开发中,我们可能会用到邮件发送的功能,比如用户生日邮件祝福,邮件验证码等功能,下面我们使用c#自带的MailMessage实现一个简单的使用邮件发送验证码的功能。
/// <summary> /// 邮件发送帮助类 /// </summary> public class EmailHelper { /// <summary> /// smtp服务器地址 /// </summary> private static readonly string Host = "smtp.163.com"; //smtp服务器端口号 private static readonly int Port = 25; //邮箱账号 private static readonly string UserName = ""; //邮箱密码 private static readonly string Password = ""; //发送方邮箱 private static readonly string From = ""; public static void Send(string subject, string body, string to) { MailMessage emailMessage = new MailMessage(); //收件人地址 emailMessage.To.Add(to); //发件人地址 emailMessage.From = new MailAddress(From); //邮件主题 emailMessage.Subject = subject; //邮件内容 emailMessage.Body = body; emailMessage.IsBodyHtml = true; //发送邮件的优先级 emailMessage.Priority = MailPriority.High; SmtpClient smtpClient = new SmtpClient(); //指定邮件服务器 smtpClient.Host = Host; //SMTP服务器端口 smtpClient.Port = Port; //发件人邮箱的用户名和密码,如果启用了授权码,则我们的密码应该为授权码而不是密码 smtpClient.Credentials = new NetworkCredential(UserName, Password); try { //发送邮件 smtpClient.Send(emailMessage); } catch (SmtpException ex) { LoggerManager.Instance.Logger_Info(ex.Message); } catch (Exception ex) { LoggerManager.Instance.Logger_Info(ex.Message); } } }
微信扫码查看本文
发表评论