C#邮件发送

HTML代码:主要就是一个form表单,使用post提交表单

   <form method="post" action="/DatabaseBackup/Date/SendMails" id="formEmail"style="position:absolute;left:488px;top:124px;">
                <ul class="formbox">
                    <li>
                        <label >发件人Email:</label><input type="text"  placeholder="请输入邮箱名称" required="" name="Email" class="text" id="email" />
                    </li>

                    <li>
                        <label>收件人Email:</label><input type="text" placeholder="请输入邮箱名称" required="" name="Emails" class="text" id="trueName" />
                    </li>

                    <li>
                        <label>主题:</label><input type="text" name="PostboxTheme" class="text" id="buildTitle" />
                    </li>
                    <li>
                        <label>正文:</label><input style="height:26px" type="text" name="PostboxContent" class="text" id="buildType" />
                    </li>
              
                    <li >
                        <label>用户名:</label><input type="text" name="UserName" placeholder="账号" required="" class="text" id="PhoneCall" />
                    </li>
                    @*<li style="position:absolute;left:124px;top:225px">
                        <label>密码:</label><input type="text" name="Password" placeholder="第三方密码" required="" class="text" id="Password" />
                    </li>*@
                    <li>
                        <label>密码:</label><input type="password" name="Password" placeholder="第三方密码" required="" class="text" id="Password" />
                    </li>
                    <li>
                        <label>&nbsp;</label><p type="button"  class="btnimg" value="发送" onclick="btEmail()" style="position:absolute;left:205px;top:300px;" />
                      
                    </li>
                </ul>
            </form>

JS:将获取到的信息提交到控制层

            //提交
            function btEmail() {
                var Emails = $("#email").val(); var PostboxTheme = $("#buildTitle").val();
                var PostboxContent = $("#buildType").val();
                var Email = $("#trueName").val();
                var UserName = $("#PhoneCall").val();
                var Password = $("#Password").val();
                if (Emails != "" && Email != "" && UserName != "" && Password != "") {
                    $("#formEmail").ajaxSubmit(function (msg) {
                        if (msg == true) {
                            alert("发送成功")
                        } else {
                            alert("发送失败");
                        }
                    })
                }

            }

定义一个发送邮件的类:其中需要引用两个命名控件,分别为SNet.Mail(允许程序使用简单邮件传输协议)、Net.Mime(Internet邮件交换标头)

​        private MailMessage mMailMessage;   //主要处理发送邮件的内容(如:收发人地址、标题、主体、图片等等)
        private SmtpClient mSmtpClient; //主要处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式等等)
        private int mSenderPort;   //发送邮件所用的端口号(htmp协议默认为25)
        private string mSenderServerHost;    //发件箱的邮件服务器地址(IP形式或字符串形式均可)
        private string mSenderPassword;    //发件箱的密码
        private string mSenderUsername;   //发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为: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">发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为: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 Email(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 e)
            {
                throw e;
                //Console.WriteLine(ex.ToString());
            }
        }​

邮件的发送:

  /// <summary>
        /// 邮件的发送
        /// </summary>
        /// <returns>发送成功返回true,否则返回false</returns>
        public bool Send()
        {
            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 e)
            {
                Console.WriteLine(e);
                return false;
            }
            return true;
        }

添加附件

///<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 = File.GetCreationTime(path[i]);
                    disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                    disposition.ReadDate = File.GetLastAccessTime(path[i]);
                    mMailMessage.Attachments.Add(data);
                }
            }
            catch (Exception ex)
            {
                throw ex;//Console.WriteLine(ex.ToString());
            }
        }

Controller:代理邮箱服务器也可以使用163邮箱,(不管是QQ邮箱,还是163邮箱,前提双方都需要开通smtp协议,可到邮箱设置里开通。)里面的端口一般为25。

 public ActionResult SendMails(string PostboxTheme, string Emails, string PostboxContent, string Email, string UserName, string Password)
        {

            string senderServerIp = "smtp.qq.com";   //使用qq代理邮箱服务器
            string toMailAddress = Emails;              //要发送对象的邮箱
            string fromMailAddress = Email;//你的邮箱
            string subjectInfo = PostboxTheme;                  //主题
            string bodyInfo = "<p>" + PostboxContent + "</p>";
            string mailUsername = UserName;             
            string mailPassword = Password; 
            string mailPort = "25";                      


            Email myEmail = new Email(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, true, true);

            //添加附件
            //email.AddAttachments(attachPath);

            if (myEmail.Send())
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

效果:

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值