代码改变世界

C# 生成csv文件并发送邮件

2021-06-04 18:59  skye_Jia  阅读(171)  评论(0编辑  收藏  举报

生成csv文件存到MemoryStream中

读取MemoryStream发送邮件,不进行文件本地保存直接发送.

使用outlook邮箱发送代码,其他邮箱跟换smtp 和 port即可

public static bool SendEmailSmtp(string email,string content, string sender, string title,string file, Attachment data1=null)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();//实例化对象
                mailMsg.From = new MailAddress(emailAddress, sender);//源邮件地址和发件人
                mailMsg.To.Add(new MailAddress(email));//收件人地址
                mailMsg.Subject = title;//发送邮件的标题   "比率测试邮件-发送小票信息"
                StringBuilder sb = new StringBuilder();
                sb.Append(content);
                mailMsg.Body = sb.ToString();//发送邮件的内容
                mailMsg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 
                mailMsg.IsBodyHtml = true;//是否是HTML邮件 
                //指定smtp服务地址(根据发件人邮箱指定对应SMTP服务器地址)
                SmtpClient client = new SmtpClient();//格式:smtp.126.com  smtp.164.com
                client.Host = "smtp-mail.outlook.com";//smtp.qq.com
                //要用587端口
                client.Port = 587;//端口 587

                client.EnableSsl = true;
                //通过email 和password验证发件人身份
                client.Credentials = new NetworkCredential(emailAddress, "123456789");

                if (!string.IsNullOrEmpty(file))
                {
                    //add file
                    Attachment data = new Attachment(file);
                    mailMsg.Attachments.Add(data);
                }
                if (data1 != null)
                {
                    mailMsg.Attachments.Add(data1);
                }
                try
                {
                    client.Send(mailMsg);
                }
                catch (SmtpException ex)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

 

csv存文件流代码:

/// <summary>
        /// create csv file stream and send email
        /// </summary>
        /// <typeparam name="T">数据model</typeparam>
        /// <param name="fileName">文件名称</param>
        /// <param name="listModel"></param>
        /// <param name="email">多邮箱处理</param>
        /// <returns></returns>
        public static bool SaveAsCSV<T>(string fileName, List<T> listModel, string[] email) where T : class, new()
        {
            bool sendemail = false;
            try
            {
                StringBuilder sb = new StringBuilder();
                //通过反射 显示要显示的列
                BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;//反射标识
                Type objType = typeof(T);
                PropertyInfo[] propInfoArr = objType.GetProperties(bf);
                #region csv heard
                string header = string.Empty;
                List<string> listPropertys = new List<string>();
                foreach (PropertyInfo info in propInfoArr)
                {
                    if (string.Compare(info.Name.ToUpper(), "ID") != 0) //不考虑自增长的id或者自动生成的guid等
                    {
                        if (!listPropertys.Contains(info.Name))
                        {
                            listPropertys.Add(info.Name);
                        }
                        header += info.Name + ",";
                    }
                }
                sb.AppendLine(header.Trim(','));
                UnicodeEncoding uniEncoding = new UnicodeEncoding();
                byte[] firstString = uniEncoding.GetBytes(sb.ToString());
                MemoryStream stream = new MemoryStream();
                stream.Write(firstString, 0, firstString.Length);
                #endregion
                #region csv content
                StringBuilder sb2 = new StringBuilder();
                foreach (T model in listModel)
                {
                    string strModel = string.Empty;
                    foreach (string strProp in listPropertys)
                    {
                        foreach (PropertyInfo propInfo in propInfoArr)
                        {
                            if (string.Compare(propInfo.Name.ToUpper(), strProp.ToUpper()) == 0)
                            {
                                PropertyInfo modelProperty = model.GetType().GetProperty(propInfo.Name);
                                if (modelProperty != null)
                                {
                                    object objResult = modelProperty.GetValue(model, null);
                                    string result = ((objResult == null) ? string.Empty : objResult).ToString().Trim();
                                    if (result.IndexOf(',') != -1)
                                    {
                                        result = "\"" + result.Replace("\"", "\"\"") + "\""; //特殊字符处理 ?
                                    }
                                    if (!string.IsNullOrEmpty(result))
                                    {
                                        Type valueType = modelProperty.PropertyType;
                                        if (valueType.Equals(typeof(Nullable<decimal>)) || valueType.Equals(typeof(decimal)))
                                        {
                                            result = decimal.Parse(result).ToString("F2");
                                        }
                                        else if (valueType.Equals(typeof(Nullable<double>)) || valueType.Equals(typeof(double)))
                                        {
                                            result = double.Parse(result).ToString("G");
                                        }
                                        else if (valueType.Equals(typeof(Nullable<float>)) || valueType.Equals(typeof(float)))
                                        {
                                            result = float.Parse(result).ToString("G");
                                        }
                                    }
                                    strModel += result + ",";
                                }
                                else
                                {
                                    strModel += ",";
                                }
                                break;
                            }
                        }
                    }
                    strModel = strModel.Substring(0, strModel.Length - 1);
                    sb2.AppendLine(strModel);
                }
                byte[] secondString = uniEncoding.GetBytes(sb2.ToString());
                int count = 0;
                while (count < secondString.Length)
                {
                    stream.WriteByte(secondString[count++]);
                }
                #endregion
                //Set the position to the beginning of the stream.
                stream.Seek(0, SeekOrigin.Begin);
                Attachment data = new Attachment(stream, fileName);

                foreach (var item in email)
                {
                    sendemail =SendEmailSmtp(item, "Please check the report today", "test", "report test", "", data);
                }

            }
            catch (Exception ex)
            {
                sendemail = false;
            }
            return sendemail;
        }
View Code