.NET如何基于SMTP协议发送邮件

SMTP是一种提供可靠且有效的电子邮件传输的协议。SMTP是建立在FTP文件传输服务上的一种邮件服务,主要用于系统之间的邮件信息传递,并提供有关来信的通知。

以Winform为例:

首先需要引用

using System.Net.Mail;
using System.Net.Mime;

按钮的点击事件

 private void button1_Click(object sender, EventArgs e)
        {
            SendEmail();
        }
 public bool SendEmail()
        {
            bool bResult = true;
            string sResult = string.Empty;
            try
            {

                string strSQL = string.Empty;
                DataTable dt = new DataTable();
                string TimeNow = string.Empty;
                DataTable dtReport = null;
                List<string> lsCode = null;

                //TimeNow = System.DateTime.Now.AddHours(-2).ToString("yyyy-MM-dd HH:mm:ss");

                #region 短缺发料报表
                //每天上班8点发送前一天的报表,只发送一次
                //if (System.DateTime.Now.Hour.ToString() == "8")
                //{
                TimeNow = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                try
                {
                    string sSubject = string.Empty;
                    string sTitle = string.Empty;
                    string sBody = string.Empty;
                    string BatchCode = string.Empty;

                    //附件路径
                    string DicPath = string.Empty;
                    string attachName = string.Empty;
                    string attachPath = string.Empty;
                    string sPath = string.Empty;
                    string sFile = string.Empty;

                    //邮件内容
                    string sContent = "<p>Dear Receiver:</p><p>You have a warning report of picking list, kindly check it.</p><p>System email, please don’t reply directly.</p>";

                    DataTable dtEmailUser = new DataTable();

                    #region 发送
                    strSQL = "select * from v_storage_list where run_status not in('Selected','Enable')";
                    sSubject = "WO Warning List";
                    sTitle = "<tr><td style=\"width:10%\" align=\"center\">WO ID</td><td style=\"width:10%\" align=\"center\">BOX_BARCODE</td></tr>";
                   
                    sBody = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">" + sTitle + sBody + "</table>";

                    //sjw 20220216 增加内容
                    sBody = string.Format("{0}{1}", sContent, sBody);
                    #endregion
                    string senderServerIp = textBox1.Text; //发件服务器
                    string mailPort = "25"; //发送邮件所用的端口号(htmp协议默认为25)
                    string fromMailAddress = "";//发件人可以为空               
                    string subjectInfo = sSubject;
                    string bodyInfo = sBody;
                    string mailUsername = string.Empty;//发件箱的用户名(即@符号前面的字符串,例如:[email protected],用户名为:hello)
                    string mailPassword = string.Empty; //发件人邮箱密码



                    string toMailAddress = string.Empty;

                    toMailAddress = textBox2.Text;
                    EmailHelper email = new EmailHelper(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, false, false);
                    email.AddAttachments(attachPath);
                    bResult = email.Send();
                }
                catch (Exception ex)
                {
                    bResult = false;
                    sResult = ex.Message;
                }
                //}

                #endregion
            }
            catch (Exception ex)
            {
                bResult = false;
                sResult = ex.Message;
            }
            return bResult;
        }

添加一个Helper类EmailHelper

 public class EmailHelper
    {
        private MailMessage mMailMessage;   //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)
        private SmtpClient mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)
        private int mSenderPort;   //发送邮件所用的端口号(htmp协议默认为25)
        private string mSenderServerHost;    //发件箱的邮件服务器地址(IP形式或字符串形式均可)
        private string mSenderPassword;    //发件箱的密码
        private string mSenderUsername;   //发件箱的用户名(即@符号前面的字符串,例如:[email protected],用户名为:hello)
        private bool mEnableSsl;    //是否对邮件内容进行socket层加密传输
        private bool mEnablePwdAuthentication;  //是否对发件人邮箱进行密码验证

        ///<summary>
        /// 构造函数
        ///</summary>
        ///<param name="server">发件箱的邮件服务器地址</param>
        ///<param name="toMail">收件人地址(可以是多个收件人,程序中是以“;"进行区分的)</param>
        ///<param name="fromMail">发件人地址</param>
        ///<param name="subject">邮件标题</param>
        ///<param name="emailBody">邮件内容(可以以html格式进行设计)</param>
        ///<param name="username">发件箱的用户名(即@符号前面的字符串,例如:[email protected],用户名为:hello)</param>
        ///<param name="password">发件人邮箱密码</param>
        ///<param name="port">发送邮件所用的端口号(htmp协议默认为25)</param>
        ///<param name="sslEnable">true表示对邮件内容进行socket层加密传输,false表示不加密</param>
        ///<param name="pwdCheckEnable">true表示对发件人邮箱进行密码验证,false表示不对发件人邮箱进行密码验证</param>
        public EmailHelper(string server, string toMail, string fromMail, string subject, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable)
        {
            try
            {
                mMailMessage = new MailMessage();
                mMailMessage.To.Add(toMail);
                mMailMessage.From = new MailAddress(fromMail);
                mMailMessage.Subject = subject;
                mMailMessage.Body = emailBody;
                mMailMessage.IsBodyHtml = true;//用网页形式显示内容
                mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mMailMessage.Priority = MailPriority.Normal;
                this.mSenderServerHost = server;
                this.mSenderUsername = username;
                this.mSenderPassword = password;
                this.mSenderPort = Convert.ToInt32(port);
                this.mEnableSsl = sslEnable;
                this.mEnablePwdAuthentication = pwdCheckEnable;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        ///<summary>
        /// 添加附件
        ///</summary>
        ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param>
        public void AddAttachments(string attachmentsPath)
        {
            try
            {
                string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义
                Attachment data;
                ContentDisposition disposition;
                for (int i = 0; i < path.Length; i++)
                {
                    data = new Attachment(path[i], MediaTypeNames.Application.Octet);
                    disposition = data.ContentDisposition;
                    disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);
                    mMailMessage.Attachments.Add(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        ///<summary>
        /// 邮件的发送
        ///</summary>
        public bool Send()
        {
            bool bResult = true;
            try
            {
                if (mMailMessage != null)
                {
                    mSmtpClient = new SmtpClient();
                    //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;
                    mSmtpClient.Host = this.mSenderServerHost;
                    mSmtpClient.Port = this.mSenderPort;
                    mSmtpClient.UseDefaultCredentials = false;
                    mSmtpClient.EnableSsl = this.mEnableSsl;
                    if (this.mEnablePwdAuthentication)
                    {
                        System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                        //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                        //NTLM: Secure Password Authentication in Microsoft Outlook Express
                        mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
                    }
                    else
                    {
                        mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                    }
                    mSmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    mSmtpClient.Send(mMailMessage);
                }
            }
            catch (Exception ex)
            {
                bResult = false;
                Console.WriteLine(ex.ToString());
            }
            return bResult;
        }
    }

大工告成!!!!!!!!!!!!!!!!!!!!11

如需Demo,请下载资源

猜你喜欢

转载自blog.csdn.net/qq_35262929/article/details/127051742