.NET Core 6.0发送邮件

Posted 棉晗榜

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET Core 6.0发送邮件相关的知识,希望对你有一定的参考价值。

using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppNetworkTestAndToEmail

    /// <summary>
    /// 邮件服务器类型
    /// </summary>
    internal enum ServerType
    
        /// <summary>
        /// 163邮件服务器
        /// </summary>
        SERVER_163_COM,

        /// <summary>
        /// qq邮件服务器
        /// </summary>
        SERVER_qq_COM,
    

    /// <summary>
    /// 发送邮件处理类
    /// </summary>
    internal class SendEmailTool
    

        /// <summary>
        /// 文件
        /// </summary>
        const string path = "";

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailFrom">发件人</param>
        /// <param name="mailTo">收件人</param>
        /// <param name="title">标题</param>
        /// <param name="content">发送内容</param>
        /// <param name="mailFromAccount">发件人账号</param>
        /// <param name="mailPassword">收件人邮箱授权码</param>
        /// <param name="serverType">服务器类型;</param>
        internal static void TestSmtpClient(string mailFrom, string mailTo, string title, string content, string mailFromAccount, string mailPassword, ServerType serverType)
        
            MailMessage mymail = new MailMessage();
            mymail.From = new System.Net.Mail.MailAddress(mailFrom);
            mymail.To.Add(mailTo);
            mymail.Subject = title;
            mymail.Body = content;
            mymail.IsBodyhtml = true;
            //mymail.Attachments.Add(new Attachment(path));

            System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();

            smtpclient.Timeout = 8000;//毫秒
            smtpclient.UseDefaultCredentials = false;
            smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;

            if (serverType == ServerType.SERVER_163_COM)
            
                smtpclient.Port = 25;
                smtpclient.Host = "smtp.163.com";
            
            else
            
                //smtpclient.Port = 465;
                smtpclient.Port = 587;
                smtpclient.Host = "smtp.qq.com";
            

            smtpclient.EnableSsl = true;
            smtpclient.Credentials = new System.Net.NetworkCredential(mailFromAccount, mailPassword);
            try
            
                smtpclient.Send(mymail);
                LogHelpter.AddLog($"发送成功,接收人mailTo,标题=title,内容=content");
            
            catch (Exception ex)
            
                LogHelpter.AddLog($"发送邮件失败.请检查.接收人mailTo,标题=title,内容=content" + ex.Message, null, "emailError");
            
        
    


LogHelpter

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppNetworkTestAndToEmail

    /// <summary>
    /// 写本地日志。日志文件自动删除历史的,保留最近32个日志文件。
    /// </summary>
    public class LogHelpter
    
        /// <summary>
        /// 最多记录32个日志文件,其他的删除历史文件
        /// </summary>
        const int MAX_FILE_COUNT = 22;

        /// <summary>
        /// 文件保存的目录
        /// </summary>
        static string fileSaveDir = "";

        /// <summary>
        /// 限制文件生成大小,258000字节,大约253kb
        /// </summary>
        const long fileBytes = 258000;

        private readonly static object lockObj = new object();

        static LogHelpter()
        
            //删除超过指定数量的历史文件    
            Task.Run(() =>
            
                while (true)
                
                    try
                    
                        //自动删除文件,
                        string[] filePathArr = System.IO.Directory.GetFileSystemEntries(fileSaveDir);

                        if (filePathArr == null || filePathArr.Length == 0)
                        
                            goto DO_SELEEP;
                        
                        List<FileInfo> files = new List<FileInfo>();
                        foreach (var item in filePathArr)
                        
                            //Console.WriteLine("日志文件:" + item);
                            System.IO.FileInfo fileInfo = new System.IO.FileInfo(item);
                            files.Add(fileInfo);
                        
                        var del_files = files.OrderByDescending(g => g.LastWriteTime).Skip(MAX_FILE_COUNT);
                        if (del_files == null || del_files.Count() == 0)
                        
                            goto DO_SELEEP;
                        
                        foreach (var file in del_files)
                        
                            file.Delete();
                        
                    
                    catch (Exception ex)
                    
                        Console.WriteLine("LogHelpter执行删除文件功能异常," + ex.Message);
                    
                DO_SELEEP:
                    System.Threading.Thread.Sleep(20000);
                
            );

        

        /// <summary>
        /// fileFolderPath为文件保存目录
        /// </summary>
        /// <param name="fileFolderPath">文件保存目录</param>
        /// <param name="fileNameNoExtension"></param>
        /// <param name="fileNamePrefix">文件名前缀</param>
        /// <returns></returns>
        static string GetNewFileName(string fileFolderPath, string fileNameNoExtension, string fileNamePrefix = null)
        
            string fileName = string.Empty;

            //文件名前缀
            fileNamePrefix = string.IsNullOrWhiteSpace(fileNamePrefix) ? "" : fileNamePrefix;
            int index = 1;
            if (fileNameNoExtension.LastIndexOf('_') == -1)
            
                // fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_" + index + ".log");
            
            else
            
                var arr = fileNameNoExtension.Split('_');
                int.TryParse(arr[arr.Length - 1], out index);
                if (index == 0 || index > 900)
                
                    index = 1;
                
            
            fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_" + index + ".log");
            while (File.Exists(fileName))
            
                if (File.ReadAllBytes(fileName).Length < fileBytes)
                
                    break;
                
                index++;
                fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_" + index + ".log");
            
            return fileName;
        

        const string saveFolder = "log";//日志文件保存根路径   

        /// <summary>  
        /// 日志记录,在程序执行的根目录,写入txt文件,文件固定大小,超过限定大小自动创建新日志文件
        /// </summary>  
        /// <param name="msg">记录内容</param>  
        /// <param name="storeDir">文件保存文件夹</param>  
        /// <param name="fileNamePrefix">文件名前缀_</param>  
        /// <returns></returns>  
        public static void AddLog(string msg, string storeDir = null, string fileNamePrefix = null)
        
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "> " + msg);
            lock (lockObj)
            
                try
                
                    //文件名前缀
                    fileNamePrefix = string.IsNullOrWhiteSpace(fileNamePrefix) ? "" : fileNamePrefix + "_";

                    string fileFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, saveFolder);
                    if (!string.IsNullOrWhiteSpace(storeDir))
                    
                        fileFolderPath = Path.Combine(fileFolderPath, storeDir);
                    
                    if (Directory.Exists(fileFolderPath) == false)
                    
                        Directory.CreateDirectory(fileFolderPath);
                    
                    fileSaveDir = fileFolderPath;
                    string fileName = string.Empty;

                    string[] files = Directory.GetFiles(fileFolderPath);
                    if (files.Length == 0)
                    
                        fileName = Path.Combine(fileFolderPath, fileNamePrefix + DateTime.Now.ToString("yyyy-MM-dd") + "_1.log");
                        goto DO_WRITE;
                    
                    //string[] files2 = files.OrderByDescending(x => x).ToArray();
                    string[] files2 = files.OrderByDescending(x => int.Parse(x.Substring(x.LastIndexOf("_")).Split("_")[1].Split(".")[0])).ToArray();
                    FileInfo fileInfo = new FileInfo(files2[0]);
                    string fileNameNoExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
                    fileName = GetNewFileName(fileFolderPath, fileNameNoExtension, fileNamePrefix);

                DO_WRITE:
                    FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write);
                    string msg2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ">" + msg + System.Environment.NewLine;
                    byte[] logBytes = UTF8Encoding.UTF8.GetBytes(msg2);
                    fs.Write(logBytes, 0, logBytes.Length);
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();
                    //  tishiMsg = "写入日志成功"; 
                
                catch (Exception ex)
                
                    Console.WriteLine("LogHelpter日志写入异常:" + ex.ToString());
                
            
        
    


调用参考

 string mailFrom = "1122222@163.com";
 string mailTo = "3333333@163.com";
 string mailAccount = "555555@163.com";
 string password = "16113333mailqx";//客户端授权码
 string title = "测试发送标题";
 string content = "测试发送内容" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 SendEmailTool.TestSmtpClient(mailFrom, mailTo, title, content, mailAccount, password,ServerType.SERVER_163_COM);


以上是关于.NET Core 6.0发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

FluentEmail - 适用于 .NET 和 .NET Core 的邮件发送库

asp.net core 发送QQ邮件

Net Core 2.2 - Docker 容器无法发送邮件

如何在 ASP.NET Core 中发送邮件

.net core 发送邮件

愚公系列2023年02月 .NET CORE工具案例-使用MailKit使用SMTP协议进行邮件发送