C#使用Smtp协议发送邮件

使用Smtp协议发送邮件

发送代码,Mail类

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace Smtp
{
    public class Mail
    {
        private string sender;
        /// <summary>
        /// 发送人
        /// </summary>
        public string Sender
        {
            get
            {
                return sender;
            }
            set
            {
                sender = value;
            }
        }

        private string senderMail;
        /// <summary>
        /// 发送人邮箱
        /// </summary>
        public string SenderMail
        {
            get
            {
                return senderMail;
            }
            set
            {
                senderMail = value;
            }
        }

        private string senderPw;
        /// <summary>
        /// 发送人密码
        /// </summary>
        public string SenderPw
        {
            get
            {
                return senderPw;
            }
            set
            {
                senderPw = value;
            }
        }

        private string smtpServer;
        /// <summary>
        /// smtpServer地址
        /// </summary>
        public string SmtpServer
        {
            get
            {
                return smtpServer;
            }
            set
            {
                smtpServer = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender">委托发件人</param>
        /// <param name="sender">委托发件人邮件地址</param>
        /// <param name="senderPw">密码</param>
        /// <param name="ewsUrl">smtpServer地址</param>
        public Mail(string sender, string senderMail, string senderPw, string smtpServer)
        {
            this.sender = sender;
            this.senderMail = senderMail;
            this.senderPw = senderPw;
            this.smtpServer = smtpServer;
        }

        public Mail()
        {
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <param name="receiver"></param>
        public void Send(string title, string body, string[] receiver)
        {
            SmtpClient _smtpClient = new SmtpClient();
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            _smtpClient.Host = this.smtpServer; ;//指定SMTP服务器
            _smtpClient.EnableSsl = true;
            _smtpClient.Port = 587;
            _smtpClient.Credentials = new System.Net.NetworkCredential(this.sender, this.senderPw);//用户名和密码

            for (int i = 0; i < receiver.Length; i++)
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                ServicePointManager.ServerCertificateValidationCallback =
delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
                MailMessage _mailMessage = new MailMessage(this.senderMail, receiver[i]);
                _mailMessage.Subject = title;//主题
                _mailMessage.Body = body;//内容
                _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
                _mailMessage.IsBodyHtml = true;//设置为HTML格式
                _mailMessage.Priority = MailPriority.High;//优先级
                //Attachment am = new Attachment(attachment, "attachment");
                //_mailMessage.Attachments.Add(am);
                _smtpClient.Send(_mailMessage);
            }

        }
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            //if (sslPolicyErrors == SslPolicyErrors.None)
            //    return true;
            //else
            //    return true;
            // If there are no errors, then everything went smoothly.
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            // Note: MailKit will always pass the host name string as the `sender` argument.
            //var host = (string)sender;
            string host = sender as string;
            if (host == null)
            {
                // Handle the case where sender is not a string
                Console.WriteLine("Sender parameter is not a valid string.");
                return false;
            }
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                // This means that there are errors in the certificate chain. You can inspect the chain errors and handle them accordingly.
                foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                {
                    Console.WriteLine("Certificate chain error: " + chainStatus.StatusInformation);
                }
                return false;
            }
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
            {
                // This means that the remote certificate is unavailable. Notify the user and return false.
                Console.WriteLine("The SSL certificate was not available for {0}", host);
                return false;
            }

            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
            {
                // This means that the server's SSL certificate did not match the host name that we are trying to connect to.
                var certificate2 = certificate as X509Certificate2;
                var cn = certificate2 != null ? certificate2.GetNameInfo(X509NameType.SimpleName, false) : certificate.Subject;

                Console.WriteLine("The Common Name for the SSL certificate did not match {0}. Instead, it was {1}.", host, cn);
                return false;
            }

            // The only other errors left are chain errors.
            Console.WriteLine("The SSL certificate for the server could not be validated for the following reasons:");

            // The first element's certificate will be the server's SSL certificate (and will match the `certificate` argument)
            // while the last element in the chain will typically either be the Root Certificate Authority's certificate -or- it
            // will be a non-authoritative self-signed certificate that the server admin created. 
            foreach (var element in chain.ChainElements)
            {
                // Each element in the chain will have its own status list. If the status list is empty, it means that the
                // certificate itself did not contain any errors.
                if (element.ChainElementStatus.Length == 0)
                    continue;

                Console.WriteLine("\u2022 {0}", element.Certificate.Subject);
                foreach (var error in element.ChainElementStatus)
                {
                    // `error.StatusInformation` contains a human-readable error string while `error.Status` is the corresponding enum value.
                    Console.WriteLine("\t\u2022 {0}", error.StatusInformation);
                }
            }

            return false;
        }
        /// <summary>
        /// 发送邮件,带附件
        /// </summary>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <param name="receiver"></param>
        /// <param name="attachment">附件</param>
        public void Send(string title, string body, string receiver, System.IO.Stream attachment)
        {
            SmtpClient _smtpClient = new SmtpClient();
            _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            _smtpClient.Host = this.smtpServer; ;//指定SMTP服务器
            _smtpClient.Credentials = new System.Net.NetworkCredential(this.sender, this.senderPw);//用户名和密码

            MailMessage _mailMessage = new MailMessage(this.senderMail, receiver);
            _mailMessage.Subject = title;//主题
            _mailMessage.Body = body;//内容
            _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
            _mailMessage.IsBodyHtml = true;//设置为HTML格式
            _mailMessage.Priority = MailPriority.High;//优先级
            Attachment am = new Attachment(attachment, "attachment");
            _mailMessage.Attachments.Add(am);
            _smtpClient.Send(_mailMessage);
        }
    }
}

测试调用,Program类

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Text;

namespace SendMail
{
    class Program
    {
        static void Main(string[] args)
        {
            Smtp.Mail mail = new Smtp.Mail();
            mail.Sender = "Test";
            mail.SenderMail = "Test@mail.com";
            mail.SenderPw = "Pass@word";
            mail.SmtpServer = "IP地址";
            //收件人列表
            string temp = "test@mail.com;test2@mail.com;";
            string[] res = temp.Split(';');
            string content ="邮件内容";
            for (int i = 0; i < 2; i ++)
            {
                Console.WriteLine("开始发送第" + i.ToString());
                mail.Send("邮件测试  " + i.ToString(), content, res);
            }
            Console.ReadLine();
     	}
  	}
}
相关推荐
用户37215742613512 小时前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
公子小六17 小时前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技18 小时前
第6章第4节:自定义分词器
开发语言·c#
zhanghaha131419 小时前
C# 系列教程_12 字符串 string 保姆级系统教程(面向新手,大量示例 + 原理讲解)
开发语言·数据库·c#
Coder_Shenshen1 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
寂寞的船2 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
1-1=02 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
波力海苔夹心脆6754 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
AI导出鸭PC端4 天前
Perplexity批量导出没有PDF模式?AI导出鸭插件补上最后一块拼图
人工智能·pdf·c#·ai导出鸭
Risehuxyc4 天前
C# 选用更流行的语言版本
c#