使用SMTP发送邮件

时间:2022-06-01 19:28:47

先定义一个邮件实体:

public class EntityMail
    {
        /// <summary>
        /// 发件人
        /// </summary>
        public string From { get; set; }
        /// <summary>
        /// 收件人
        /// </summary>
        public string To { get; set; }
        /// <summary>
        ///
        /// </summary>
        public string Cc { get; set; }
        /// <summary>
        ///
        /// </summary>
        public string Bcc { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Subject { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Body { get; set; }
        /// <summary>
        /// 附件
        /// </summary>
        public string Attachments { get; set; }
        /// <summary>
        ///
        /// </summary>
        public int RetryTime { get; set; }
        /// <summary>
        ///
        /// </summary>
        public string Importance { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
    }
/// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mail">邮件</param>
        public static void SendBySmtp(EntityMail mail)
        {
            var smtpHost = ConfigurationManager.AppSettings["SmtpServerHost"];
            if (smtpHost == null)
            {
                throw new System.Exception("AppSettings中SmtpServerHost没有配置。");
            }

            ;
            if (!int.TryParse(Common.GetAppSetting("SmtpServerPort"), out port))
            {
                port = ;
            }
            // host:邮件服务器,port:端口
            SmtpClient smtpClient = new SmtpClient(smtpHost, port);
            // 是否启用安全套接字层加密连接
            smtpClient.EnableSsl = false;
// 邮件对象
            MailMessage mailMessage = new MailMessage(mail.From, mail.To, mail.Subject, mail.Body);
            // 邮件优先级
            mailMessage.Priority = MailPriority.Normal;
            // 发送方身份验证
            smtpClient.Credentials = new NetworkCredential(mail.From, mail.Password);
            //开始发送
            smtpClient.Send(mailMessage);
        }