C# 如何實現郵件發送


調用發送

try
            {
                P2BEmail email = new P2BEmail();
                email.fromEmail = txtfromEmail.Text; //  QQ郵箱
                email.fromPwd = txtfrompwd.Text;    //  QQ郵箱授權碼
                email.emailType = txtemailtype.Text;  //  smtp.qq.com
                email.SendEmail(txttoemail.Text, txtsubject.Text, txtbody.Text, "");
                txtmessage.Text = "成功";
            }
            catch (Exception ex)
            {

                txtmessage.Text = ex.Message + ex.StackTrace;
            }

 

郵件發送邏輯

public class P2BEmail
    {
        public string fromEmail = "XX@qq.com";//郵件發送方

        public string fromPwd = "XXXXXXXXXX"; //郵件發送方密碼/QQ授權碼

        public string emailType = "smtp.qq.com";//郵件類型 smtp.163.com.cn; smtp.qq.com.cn; smtp.126.com.cn;  smtp.sina.com.cn


        /// <summary>
        /// 發送電子郵件
        /// </summary>
        /// <param name="toEmail">接收方電子郵件</param>
        /// <param name="subject">郵件標題</param>
        /// <param name="body">郵件內空</param>
        public void SendEmail(string toEmail, string subject, string body, string attFile)
        {

            MailAddress addrFrom = new MailAddress(fromEmail, fromEmail);
            MailAddress addrTo = new MailAddress(toEmail, toEmail);
            MailMessage mm = new MailMessage(addrFrom, addrTo);
            mm.BodyEncoding = Encoding.UTF8;
            mm.IsBodyHtml = true;
            mm.Subject = subject;
            mm.Body = body;

            if (!string.IsNullOrEmpty(attFile))
            {
                Attachment att = new Attachment(attFile, MediaTypeNames.Application.Octet);
                ContentDisposition cd = att.ContentDisposition;
                cd.CreationDate = File.GetCreationTime(attFile);
                cd.ModificationDate = File.GetLastWriteTime(attFile);
                cd.ReadDate = File.GetLastAccessTime(attFile);
                mm.Attachments.Add(att);//添加附件
            }

            NetworkCredential nc = new NetworkCredential(fromEmail, fromPwd);
            SmtpClient smtp = new SmtpClient(emailType);
            smtp.EnableSsl = true;  //啟用SSl
       //  隨請求一起發送 smtp.UseDefaultCredentials
= false;
       //  郵件賬戶憑證 smtp.Credentials
= nc;
       //  郵件發送方式-網絡發送 smtp.DeliveryMethod
= SmtpDeliveryMethod.Network;
       //  服務器證書驗證回調  ServicePointManager.ServerCertificateValidationCallback
=delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };   try { smtp.Send(mm); } catch (SmtpFailedRecipientException) { smtp.Dispose(); return; } catch (Exception ex) { throw ex; } smtp.Dispose(); } }

  下載地址源碼下載.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM