其他分享
首页 > 其他分享> > .net core 带附件邮件发送

.net core 带附件邮件发送

作者:互联网

       上次简单的介绍了邮件发送功能。(https://www.cnblogs.com/zpy1993-09/p/13589065.html) 

那么一般的邮件的发送附带附件一起发送给用户的。正好最近在做一个功能,实现每天晚上特定时间,生成当日报表,发送给对应用户。至于报表如何自定生成,以前excel导入导出功能(Epplus插件),我已经介绍了(https://www.cnblogs.com/zpy1993-09/p/11726140.html)。虽 然这次用的是不同插件(NPOI插件)。其实效果都是一样的。

        我用的是.net core 控制台应用程序,定时程序用的是QuarZ任务调度的方式来实现的。完成后可以将控制台应用程序直接安装成服务器中的一个服务来独立运行。感兴趣的可以看一下以前写的ELK日志监控平台(https://www.cnblogs.com/zpy1993-09/tag/ELK/)那里有介绍如何将exe安装成服务器中的一个服务,独立运行。

下面不说了,直接上代码:

  邮件发送的通用类:

  

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Quartz.NET.Apply.Common
{
    class EMailHelper
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="list">保存附件路径,之所用数组,因为你可能不止发一个附件,而是一次多个附件</param>
        /// <param name="name">发件人名字</param>
        /// <param name="eamil">接收邮箱</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <returns>成功/失败</returns>
        public static string send(List<string> list, string name, string eamil, string title, string content)
        {

            SmtpClient client = new SmtpClient("smtp.qq.com");
            string sendEmail = "12345678@qq.com";  //你用来发送邮件的账号,一定是已经开通服务的。
            string sendpwd = "kcbglwpdsqxjce";    //你开通服务后,返回给你的授权码
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(sendEmail, sendpwd);

            MailAddress from = new MailAddress(sendEmail, name, Encoding.UTF8);//初始化发件人  

            MailAddress to = new MailAddress(eamil, "", Encoding.UTF8);//初始化收件人  

            //设置邮件内容  
            MailMessage message = new MailMessage(from, to);
            message.Body = content.Trim();
            message.BodyEncoding = Encoding.UTF8;
            message.Subject = title.Trim();
            message.SubjectEncoding = Encoding.UTF8;
            message.IsBodyHtml = false;
            for (int i = 0; i < list.Count; i++)
            {
                string fileName = list[i];
                if (!string.IsNullOrEmpty(fileName)&&FileHelper.SelectFile(list[i]))
                {
                   
                    //附件
                    Attachment myAttachment = new System.Net.Mail.Attachment(fileName, MediaTypeNames.Application.Octet);

                    //MIME协议下的一个对象,用以设置附件的创建时间,修改时间以及读取时间  
                    ContentDisposition disposition = myAttachment.ContentDisposition;
                    disposition.CreationDate = File.GetCreationTime(fileName);
                    disposition.ModificationDate = File.GetLastWriteTime(fileName);
                    disposition.ReadDate = File.GetLastAccessTime(fileName);

                    //用smtpclient对象里attachments属性,添加上面设置好的myattachment  

                    message.Attachments.Add(myAttachment);
                }
            }

           // LogHelper.AddLog("准备将运维数据发送给邮箱为 " + eamil + " 的用户。。。。。", "SendMail");
            try
            {
                client.Send(message);
                LogHelper.AddLog("已经将运维数据发送给邮箱为 " + eamil + " 的用户了。。。。。", "SendMail");
                return "邮件发送成功!";
            }
            catch (Exception ex)
            {
                LogHelper.AddLog("邮箱为 " + eamil + " 的用户了邮件发送失败了。。。。。", "SendMail");
                List<string> relist = list;
                LogHelper.AddLog("邮箱为 " + eamil + " 的用户启动了重发机制。。。。。", "SendMail");
//下面是邮件发送失败后的重发机制 Task.Run(() => { Thread.Sleep(5000);//为了防止邮件发送失败后,立刻重发,影响其他邮件发送,所以先休眠5秒,在重新发送 EMailHelper.send(list, "XX科技有限公司", eamil, "运维数据", "运维数据分析"); }); return "邮件发送失败!" + ex.Message; } } } }
LogHelper是一个日志记录类,是用来记录邮件发送日志的。
using System;
using System.Collections.Generic;
using System.Text;

namespace Quartz.NET.Apply.Common
{
   public class LogHelper
    {
        public static void AddLog(string LogContent, string FloderName)
        {
            LogContent = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss").ToString() + ":  " + LogContent;
            string strtime = DateTime.Now.ToString("yyyy-MM-dd").ToString();
            string path = "UpFile/PushLog/" + FloderName + "/" + DateTime.Now.ToString("yyyy-MM-dd").ToString() + ".txt";
            FileHelper.CreatePath("UpFile/PushLog/" + FloderName);
            if (!FileHelper.FileExist(path))
            {
                FileHelper.CreatFile(path);
            }
            FileHelper.AddSaveFile(path, LogContent, "utf-8");
        }
        /// <summary>
        /// 存放要发送的邮件附件
        /// </summary>
        /// <param name="LogContent">邮件说明</param>
        /// <param name="FloderName"></param>
        /// <param name="FileType"></param>
        public static string AddPath(string FloderName)
        {
            string path = "UpFile/SaveFile/" + FloderName + "/" ;
            FileHelper.CreatePath(FloderName);
            return path;
        }
    }
}
FileHelper是文件处理通用类:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace Quartz.NET.Apply.Common
{
    /// <summary>
    /// 系统中常用的一些IO操作:磁盘空间检测、文件创建等
    /// </summary>
    public class FileHelper
    {

        /// ******************************************************************
        #region 模板生成网页专用
        /// ******************************************************************
        /// <summary>
        /// 模板读取文件内容
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string strFileName)
        {
            string strUrlText = "";
            if (File.Exists(strFileName))
            {
                StreamReader sr = new StreamReader(strFileName, System.Text.Encoding.GetEncoding("utf-8"));
                strUrlText = sr.ReadToEnd();
                sr.Close();
            }
            return strUrlText;
        }
        /// <summary>
        /// 模板自动生成网页文件
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="sContent">文件内容</param>
        public static void CreatNewFile(string sFilePath, string sContent)
        {
            string dir = sFilePath.Substring(0, sFilePath.LastIndexOf("\\"));
            CreatFolder(dir);
            if (!File.Exists(sFilePath))
            {
                System.IO.FileStream myFileStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Create);
                myFileStream.Close();
            }
            System.IO.StreamWriter sw = new StreamWriter(sFilePath, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);
            sw.Close();
        }
        /// <summary>
        /// 模板自动生成网页文件
        /// </summary>
        /// <param name="sFilePath">文件路径</param>
        /// <param name="sContent">文件内容</param>
        /// <param name="sContent">文件编码</param>
        public static void CreatNewFile(string sFilePath, string sContent, string sEncode)
        {
            string dir = sFilePath.Substring(0, sFilePath.LastIndexOf("\\"));
            CreatFolder(dir);
            if (!File.Exists(sFilePath))
            {
                System.IO.FileStream myFileStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Create);
                myFileStream.Close();
            }
            System.IO.StreamWriter sw = new StreamWriter(sFilePath, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(sContent);
            sw.Close();
        }
        public static void CreatFolder(string directoryName)
        {
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
        }
        #endregion
        /// ******************************************************************
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string strFileName, string encoding)
        {
            string strUrlText = string.Empty;
            if (File.Exists(strFileName))
            {
                StreamReader sr = new StreamReader(strFileName, string.IsNullOrEmpty(encoding) ? System.Text.Encoding.Default : System.Text.Encoding.GetEncoding(encoding));
                strUrlText = sr.ReadToEnd();
                sr.Close();
            }
            return strUrlText;
        }
        /// ******************************************************************
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static int DeleteFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
                return 1;
            }
            else
            {
                return 0;
            }

        }
        ///******************************************************************
        /// ******************************************************************
        /// <summary>
        /// 向文件添加文本
        /// </summary>
        /// <param name="strFileName">文件路径</param>
        /// <param name="strText">文件内容</param>
        /// <param name="strEncode">存储编码 utf-8  gb2312</param>
        /// <returns></returns>
        public static bool AddSaveFile(string strFileName, string strText, string strEncode)
        {
            if (strText.Length < 1) { return false; }
            StreamWriter urlWrite = new StreamWriter(strFileName, true, Encoding.GetEncoding(strEncode));
            urlWrite.BaseStream.Seek(0, SeekOrigin.End);
            urlWrite.WriteLine("{0}\n", strText, DateTime.Now);
            urlWrite.Flush();
            // urlWrite.WriteLine(strText);
            urlWrite.Close();

            return true;
        }

        /// ******************************************************************
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        public static void DelFile(string strFileName)
        {
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
            }
        }
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void CreatFile(string strFileName)
        {
            System.IO.FileStream myFileStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Create);
            myFileStream.Close();
        }
        /// <summary>
        /// 创建目录,如果目录不存在就创建,存在则直接返回。
        /// </summary>
        /// <param name="path"></param>
        public static string CreatePath(string strPath)
        {
            if (!System.IO.Directory.Exists(strPath))
                System.IO.Directory.CreateDirectory(strPath);
            return strPath;
        }
        /// ******************************************************************
        /// <summary>
        /// 向文件添加文本
        /// </summary>
        /// <param name="strFileName">文件路径</param>
        /// <param name="strText">文件内容</param>
        /// <param name="strEncode">存储编码</param>
        /// <returns></returns>
        public static bool SaveFile(string strFileName, string strText, string strEncode)
        {
            if (strText.Length < 1) { return false; }

            StreamWriter urlWrite = new StreamWriter(strFileName, false, Encoding.GetEncoding(strEncode));
            urlWrite.Write(strText);
            urlWrite.Close();

            return true;
        }

        ///******************************************************************

        public static bool FileExist(string strPath)
        {
            return File.Exists(strPath);
        }
        ///******************************************************************
        /// <summary>
        ///   //检查并创建文件
        /// </summary>
        /// <param name="strFileName">文件全路径</param>
        /// <param name="boolDelExist">如果文件存在是否删除</param>
        /// <returns></returns>
        ///******************************************************************     
        public static string CheckAndCreateFile(string strFileName, bool boolDelExist)
        {
            strFileName = strFileName.Replace("/", "\\");
            //存在文件
            if (File.Exists(strFileName))
            {
                if (boolDelExist)
                {
                    File.Delete(strFileName);
                    CreatFile(strFileName);
                }
            }
            else //不存在文件
            {
                int end = strFileName.LastIndexOf("\\");
                if (end > 0)
                {
                    string strFolder = strFileName.Substring(0, end);
                    if (!Directory.Exists(strFolder))
                    {
                        Directory.CreateDirectory(strFolder);
                    }
                }
                CreatFile(strFileName);
            }
            return strFileName;
        }
       /// <summary>
       /// 判断文件是否存在
       /// </summary>
       /// <param name="strFileName"></param>
       /// <returns></returns>
        public static bool SelectFile(string strFileName)
        {
            strFileName = strFileName.Replace("/", "\\");
            //存在文件
            if (File.Exists(strFileName))
            {
                return true;
            }
            else //不存在文件
            {
               return false;
            }
           
        }
        public static void CreatDefaultXml(string strFileName)
        {
            string strMyXml = "<?xml version=\"1.0\" encoding=\"gb2312\"?><configuration></configuration>";
            System.IO.FileStream myFileStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Create);
            myFileStream.Close();
            StreamWriter urlWrite = new StreamWriter(strFileName, false, Encoding.GetEncoding("gb2312"));
            urlWrite.Write(strMyXml);
            urlWrite.Close();
        }
        //用户WINDOW应用程序与WEN项目CONFIG切换
        public static string GetConfigPath(string path)
        {
            string strPath = path;
            if (!System.IO.File.Exists(path) || strPath.IndexOf(":") == -1)
            {
                //string strPath1 = System.IO.Directory.GetCurrentDirectory();
                //string strPath2 = System.Environment.CurrentDirectory;
                //以上两种取个人文档地址,下面两种取WEB文件夹路径
                //strPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                strPath = System.AppDomain.CurrentDomain.BaseDirectory + path;
            }
            return strPath;
        }
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strMath">文件名</param>
        /// <returns>绝对路径</returns>
        public static string GetImgPath(string strMath)
        {
            string strPath = "\\Photo\\";
            string strMonth = DateTime.Now.Month.ToString();
            if (strMonth.Length == 1) { strMonth = "0" + strMonth; }
            strPath += DateTime.Now.Year.ToString() + strMonth + "\\";
            string strTime = DateTime.Now.ToString() + DateTime.Now.Millisecond.ToString();
            strPath += strTime.Replace(" ", "").Replace("-", "").Replace(":", "");
            if (strMath == null || strMath.Length < 1)
            {
                strPath += ".jpg";
            }
            else
            {
                strPath += "-" + strMath + ".jpg";
            }
            return strPath;
        }
        /// <summary>
        /// 判断文件名是否为浏览器可以直接显示的图片文件名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否可以直接显示</returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }

        public static string SearchConfigPath()
        {
            string BaseDic = System.AppDomain.CurrentDomain.BaseDirectory;
            int i = 0;
            DirectoryInfo info = new DirectoryInfo(BaseDic);
            while (i < 8)
            {
                //要查的目录必须是小写
                DirectoryInfo[] tempInfo = info.GetDirectories("snipconfig");
                if (tempInfo.Length > 0)
                {
                    BaseDic = tempInfo[0].FullName;
                    break;
                }
                else
                {
                    info = info.Parent;
                    tempInfo = info.GetDirectories("web");
                    if (tempInfo.Length > 0)
                    {
                        info = tempInfo[0];
                    }
                }
                i++;
            }
            return BaseDic.TrimEnd('\\');
        }

        /// <summary>
        /// 索引一个文件夹 name  size time path
        /// </summary>
        /// <param name="strDirectory">文件夹路径</param>
        public static DataTable IndexDic(string strDirectory)
        {
            DirectoryInfo directory = new DirectoryInfo(strDirectory);
            DataTable dtFile = new DataTable();
            dtFile.Columns.Add("name", typeof(string));
            dtFile.Columns.Add("size", typeof(string));
            dtFile.Columns.Add("time", typeof(string));
            dtFile.Columns.Add("path", typeof(string));
            dtFile.Columns.Add("type", typeof(string));
            DataRow newRow;
            foreach (FileInfo fi in directory.GetFiles())
            {
                //跳过临时文件
                if (fi.Name.StartsWith("~"))
                    continue;
                newRow = dtFile.NewRow();
                newRow["name"] = fi.Name;
                newRow["size"] = fi.Length / 100;
                newRow["time"] = fi.LastWriteTime.ToString();
                newRow["path"] = fi.FullName;
                newRow["type"] = fi.Extension.Replace(".", "");
                dtFile.Rows.Add(newRow);
            }
            return dtFile;
        }
        /// <summary>
        /// 获取应用程序所在根目录,并拼接传入的目录名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCurrPath(string name)
        {
            return System.AppDomain.CurrentDomain.BaseDirectory + name;
        }

    }
}

 

效果图:

 

 

 

 

 

 
 

标签:core,return,string,System,static,附件,net,public,strFileName
来源: https://www.cnblogs.com/zpy1993-09/p/14286542.html