C#发邮件

一、两种发送邮件的方法

 

有用到两种方式发邮件,一种是用System.Web.Mail类,另一种是System.Net.Mail类。

System.Net.Mail是作为System.Web.Mail的替代存在的。

System.Web.Mail使用时会提示已过时,但目前任然可以正常使用。

 

 

二、遇到的问题

 

我在使用System.Net.Mail发邮件的时候遇到一个问题,如果是用的阿里云服务器,阿里云服务器把邮件的默认25端口给禁用掉了(为的是不让邮件泛滥),25端口被封,阿里云发送SMTP邮件失败。

在网上找了一些资料,主要有以下几种方法解决:

  1、在阿里云平台申请解封TCP 25 端口 (Outbound)

  2、更换端口号为465 或 587 ;

  3、服务器前缀加上 ssl://

  4、使用System.Web.Mail发送邮件

 

2和3我都试用无果,阿里云服务器还是发送邮件失败,最后使用System.Web.Mail发送成功,要是有别的更好的方法请大家告知,谢谢谢谢~~

 

三、示例

这里我把发邮件一些相关的参数配置在ini文件里(smt服务器、端口号、发件人邮箱、发件人密码、发件人昵称、接收人邮箱)

#region 读写本地IN文件

        public static string ReadIniFile(string iniFileName, string section, string key)
        {
            string strFileName = GetRootPath() + "\\" + iniFileName;

            if (!System.IO.File.Exists(strFileName))
            {
                FileStream fs = System.IO.File.Create(strFileName);
                fs.Close();
            }

            TWays.IniFile localIniFile = new TWays.IniFile(strFileName);

            return localIniFile.ReadInivalue(section, key);
        }

        public static void WriteIniFile(string iniFileName, string section, string key, string value)
        {
            string strFileName = GetRootPath() + "\\" + iniFileName;
            if (!System.IO.File.Exists(strFileName))
            {
                FileStream fs = System.IO.File.Create(strFileName);
                fs.Close();
            }

            TWays.IniFile localIniFile = new TWays.IniFile(strFileName);

            localIniFile.WriteInivalue(section, key, value);
        }

        #endregion



        public const string MonitorLogFileName = "WmsImportSheetLog.Log";

        public const string MailSetIniFileName = "MailSet.ini";
        public const string MailSetSectionOption = "Option";
        public const string MailSetKeySmtpServer = "SmtpServer";//smtp服务器
        public const string MailSetKeySmtpPort = "SmtpPort";//端口号
        public const string MailSetKeySendAddr = "SendAddr";//发件人邮箱
        public const string MailSetKeySendPwd = "SendPwd";//发件人密码
        public const string MailSetKeySendUser = "SendUser";//发件人名称,可随意定义
        public const string MailSetKeyReceiAddr = "ReceiAddr";//收件人邮箱

//如果ini文件内没有内容就设置默认值
public void WriteMailSet()
        {
            string strFileName = BusiUtils.GetRootPath() + "\\" + Constant.MailSetIniFileName;

            if (!System.IO.File.Exists(strFileName))
            {
                BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpServer, "smtp.163.com");
                BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpPort, "465");
                BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendAddr, "lala12121@163.com");

                string sendPwd = "lalala2017";
                sendPwd = TWays.Utils.EncryptString(sendPwd);

                BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendPwd, sendPwd);
                BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendUser, "系统管理员");
          //多个收件人用 ' ;' 号隔开
                BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeyReceiAddr, "1234@qq.com;5678@qq.com;2579@qq.com;");
                
            }
        } 

 

 

 

System.Web.Mail

 public bool Process()
        {
            bool boolReturn = false;

            try
            {
                string errorMsg = string.Empty;
                string title = "每日单据导入情况" + "-" + DateTime.Now.ToString("yyyy-MM-dd");
                string message = string.Empty;

                try
                {
                    WriteMailSet();

                    bool bl = true;
                    DataSet ds = DataAdapter.Query(SqlText.selectImportSheetErrorLog.ToUpper());

                    #region 

                    if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count <= 0)
                    {
                        message = "单据处理成功!";
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();

                        sb.Append("以下为单据导入异常的消息:\r\n\r\n");

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            bl = false;
                            sb.Append("  任务编号:" + dr["TASK_CODE"].ToString() + ",\t");
                            sb.Append("  任务名称:" + dr["TASK_NAME"].ToString() + ",\t");
                            sb.Append("  日志消息:" + dr["MEMO"].ToString());
                            sb.Append("\r\n");
                        }
                        message = sb.ToString();
                    }

                    #endregion

                    if (bl)
                    {
                        title = "[成功]" + title;
                    }
                }
                catch (Exception Ex)
                {
                    message = Ex.Message;

                    errorMsg = "邮件发送失败!错误信息:" + message;

                    message = "Error:" + Ex.Message;

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);

                    return boolReturn;
                }

                #region 发送邮件

                try
                {

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "发送" + title + "开始\r\n", true);

                    bool result = Monitor(title, message, "", "");

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "发送" + title + "结束\r\n", true);

                }
                catch (Exception Ex)
                {
                    errorMsg = "邮件发送失败!错误信息:" + Ex.Message;

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);

                    return boolReturn;
                }
                #endregion


                Result = "Succeed";
                boolReturn = true;
            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }

            return boolReturn;
        }

        private bool Monitor(string title, string message, string fileName, string shortFileName)
        {
            string smtpServer = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpServer);
            string smtpPort = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpPort);
            string sendAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendAddr);
            string sendPwd = Utils.DecryptString(BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendPwd));
            string receiAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeyReceiAddr);

            string errorMsg = string.Empty;
            
            try
            {
                System.Web.Mail.MailMessage mmsg = new System.Web.Mail.MailMessage();
                //邮件主题
                mmsg.Subject = title;
                //mmsg.BodyFormat = System.Web.Mail.MailFormat.Html;
                //邮件正文
                mmsg.Body = message;
                //正文编码
                mmsg.BodyEncoding = Encoding.UTF8;
                //优先级
                mmsg.Priority = System.Web.Mail.MailPriority.High;

                System.Web.Mail.MailAttachment data = null;
                //if (SUpFile != "")
                //{
                //    SUpFile = HttpContext.Current.Server.MapPath(SUpFile);//获得附件在本地地址
                //    System.Web.Mail.MailAttachment attachment = new System.Web.Mail.MailAttachment(SUpFile); //create the attachment
                //    mmsg.Attachments.Add(attachment); //add the attachment
                //}
                //发件者邮箱地址
                mmsg.From = string.Format("\"{0}\"<{1}>", "方予系统管理员", sendAddr);

                //收件人收箱地址
                mmsg.To = receiAddr;
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
                //用户名
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", sendAddr);
                //密码 不是邮箱登陆密码 而是邮箱设置POP3/SMTP 时生成的第三方客户端授权码
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", sendPwd);
                //端口
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", smtpPort);
                //使用SSL
                mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
                //Smtp服务器
                System.Web.Mail.SmtpMail.SmtpServer = smtpServer;

                System.Web.Mail.SmtpMail.Send(mmsg);

                System.Threading.Thread.Sleep(20000);

            }
            catch (Exception Ex)
            {
                errorMsg = "邮件发送失败!错误信息:" + Ex.Message;
                TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                return false;
            }

            return true;
        }

 

 

 

 

System.Net.Mail

SmtpClient SmtpClient = null;   //设置SMTP协议        
MailAddress MailAddress_from = null; //设置发信人地址  当然还需要密码        
MailAddress MailAddress_to = null;  //设置收信人地址  不需要密码        
MailMessage MailMessage_Mai = null;
FileStream FileStream_my = null; //附件文件流

public bool Process()
        {
            bool boolReturn = false;

            try
            {
                string errorMsg = string.Empty;
                string title = "每日单据导入情况" + "-" + DateTime.Now.ToString("yyyy-MM-dd");
                string message = string.Empty;

                try
                {
                    WriteMailSet();

                    bool bl = true;
                    DataSet ds = DataAdapter.Query(SqlText.selectImportSheetErrorLog.ToUpper());

                    #region 

                    if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count <= 0)
                    {
                        message = "单据导入成功!";
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();

                        sb.Append("以下为单据导入异常的消息:\r\n\r\n");

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            bl = false;
                            sb.Append("  任务编号:" + dr["TASK_CODE"].ToString() + ",\t");
                            sb.Append("  任务名称:" + dr["TASK_NAME"].ToString() + ",\t");
                            sb.Append("  日志消息:" + dr["MEMO"].ToString());
                            sb.Append("\r\n");
                        }
                        message = sb.ToString();
                    }

                    #endregion

                    if (bl)
                    {
                        title = "[成功]" + title;
                    }
                }
                catch (Exception Ex)
                {
                    message = Ex.Message;

                    errorMsg = "邮件发送失败!错误信息:" + message;

                    message = "Error:" + Ex.Message;

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);

                    return boolReturn;
                }

                #region 发送邮件

                try
                {

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "发送" + title + "开始\r\n", true);

                    bool result = Monitor(title, message, "", "");

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "发送" + title + "结束\r\n", true);

                }
                catch (Exception Ex)
                {
                    errorMsg = "邮件发送失败!错误信息:" + Ex.Message;

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);

                    return boolReturn;
                }
                #endregion


                Result = "Succeed";
                boolReturn = true;
            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }

            return boolReturn;
        }

        private bool Monitor(string title, string message, string fileName, string shortFileName)
        {
            string smtpServer = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpServer);
            string smtpPort = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpPort);
            string sendAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendAddr);
            string sendPwd = Utils.DecryptString(BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendPwd));
            string receiAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeyReceiAddr);

            string errorMsg = string.Empty;

            try
            {
                //初始化Smtp服务器信息
                setSmtpClient(smtpServer, Convert.ToInt32(smtpPort));
            }
            catch (Exception Ex)
            {
                errorMsg = "邮件发送失败,请确定SMTP服务名是否正确!错误信息:" + Ex.Message;
                TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                return false;
            }
            try
            {
                //验证发件邮箱地址和密码
                setAddressform(sendAddr, sendPwd);
            }
            catch (Exception Ex)
            {
                errorMsg = "邮件发送失败,请确定发件邮箱地址和密码的正确性!错误信息:" + Ex.Message;
                TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                return false;
            }
            try
            {
                MailMessage_Mai = null;
                MailMessage_Mai = new MailMessage();
                //清空历史发送信息 以防发送时收件人收到的错误信息(收件人列表会不断重复)
                MailMessage_Mai.To.Clear();
                string[] recAddress = receiAddr.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                //添加收件人邮箱地址
                for (int i = 0; i < recAddress.Length; i++)
                {
                    MailAddress_to = new MailAddress(recAddress[i]);
                    MailMessage_Mai.To.Add(MailAddress_to);
                }

                //发件人邮箱
                MailMessage_Mai.From = MailAddress_from;
                //邮件主题
                MailMessage_Mai.Subject = title;
                MailMessage_Mai.SubjectEncoding = System.Text.Encoding.UTF8;
                //邮件正文
                MailMessage_Mai.Body = message;
                MailMessage_Mai.BodyEncoding = System.Text.Encoding.UTF8;

                //清空历史附件  以防附件重复发送
                //MailMessage_Mai.Attachments.Clear();
                //FileStream_my = new FileStream(fileName, FileMode.Open);
                //string name = FileStream_my.Name;
                ////添加附件
                //MailMessage_Mai.Attachments.Add(new Attachment(FileStream_my, shortFileName));

                //注册邮件发送完毕后的处理事件
                SmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

                //开始发送邮件
                SmtpClient.SendAsync(MailMessage_Mai, "000000000");

                System.Threading.Thread.Sleep(30000);
            }
            catch (Exception Ex)
            {
                errorMsg = "邮件发送失败!错误信息:" + Ex.Message;
                TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                return false;
            }

            return true;
        }

        #region 设置Smtp服务器信息

        /// <summary>        
        /// 设置Smtp服务器信息        
        /// </summary>        
        /// <param name="ServerName">SMTP服务名</param>        
        /// <param name="Port">端口号</param>        
        private void setSmtpClient(string ServerHost, int Port)
        {
            SmtpClient = new SmtpClient();
            SmtpClient.Host = ServerHost;//指定SMTP服务名  例如QQ邮箱为 smtp.qq.com 新浪cn邮箱为 smtp.sina.cn等            
            SmtpClient.Port = Port; //指定端口号            
            SmtpClient.Timeout = 5;  //超时时间    
            SmtpClient.EnableSsl = true; //指定 SmtpClient 使用安全套接字层 (SSL) 加密连接
        }

        #endregion

        #region 验证发件人信息

        /// <summary>        
        /// 验证发件人信息        
        /// </summary>        
        /// <param name="MailAddress">发件邮箱地址</param>        
        /// <param name="MailPwd">邮箱密码</param>        
        private void setAddressform(string MailAddress, string MailPwd)
        {
            string sendUser = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendUser);

            //创建服务器认证            
            NetworkCredential NetworkCredential_my = new NetworkCredential(MailAddress, MailPwd);
            //实例化发件人地址            
            MailAddress_from = new System.Net.Mail.MailAddress(MailAddress, sendUser, Encoding.BigEndianUnicode);
            //指定发件人信息  包括邮箱地址和邮箱密码            
            SmtpClient.Credentials = new System.Net.NetworkCredential(MailAddress_from.Address, MailPwd);
        }

        #endregion

        #region 发送邮件后所处理的函数

        private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            string errorMsg = string.Empty;
            try
            {
                if (e.Cancelled)
                {
                    errorMsg = "发送已取消!";

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                }
                if (e.Error != null)
                {
                    errorMsg = "邮件发送失败!1错误信息:" + e.Error.Message;

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                }
                else
                {
                    errorMsg = "恭喜,邮件成功发出!";

                    TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
                }

                if (FileStream_my != null)
                {
                    FileStream_my.Close();
                }
            }
            catch (Exception Ex)
            {
                errorMsg = "邮件发送失败!2错误信息:" + Ex.Message;

                TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true);
            }
        }

        #endregion

 

上一篇:go学习笔记-day20


下一篇:USACO Section 4.3 Street Race(图的连通性+枚举)