c# 两种发送邮件的方法

这篇文章主要介绍了c# 两种发送邮件的方法,帮助大家更好的理解和学习使用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
                /

本文标题为:c# 两种发送邮件的方法

基础教程推荐