C# 發送郵件附件

最近要作一個發送郵件的功能,依稀記得曾經有作過類似的東西,翻看了之前保存的項目代碼,果真有(雖然已經不記得是怎麼完成的了)。html

完整項目就不貼了,有個Helper.cs,把這個貼上來吧,實際業務須要,新增了添加附件的方法。web

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;   //發件箱的用戶名(即@符號前面的字符串,例如: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 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 = File.GetCreationTime(path[i]);
                    disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                    disposition.ReadDate = File.GetLastAccessTime(path[i]);
                    mMailMessage.Attachments.Add(data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        ///<summary>
        /// 添加附件
        ///</summary>
        ///<param name="stream">網絡附件,上傳Stream流</param>
        public void AddAttachments(Stream stream, string name)
        {
            try
            {
                //string[] path = attachmentsPath.Split(';'); //以什麼符號分隔能夠自定義
                Attachment data;
                data = new Attachment(stream, name);
                mMailMessage.Attachments.Add(data);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        ///<summary>
        /// 發送郵件
        ///</summary>
        public void Send()
        {
            try
            {
                if (mMailMessage != null)
                {
                    //創建發送對象client,驗證郵件服務器,服務器端口,用戶名,以及密碼
                    mSmtpClient = new SmtpClient();
                    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)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }

 

 添加附件,分爲絕對路徑與網絡路徑兩種api

添加絕對路徑很簡單數組

//添加本地附件
emailHelper.AddAttachments("C:\\附件1.txt");
//發送郵件
emailHelper.Send();

網絡路徑則經過Steam流上傳文件服務器

string url = "https://pic.cnblogs.com/avatar/35695/20201013225735.png";
WebClient web = new WebClient();
//從網絡路徑下載資源做爲 Byte 數組
byte[] a = web.DownloadData(url); Stream s = new MemoryStream(a); string name = url.Substring(url.LastIndexOf("."));
//經過Stream添加附件 emailHelper.AddAttachments(s,
"博客園團隊" + name);
//發送郵件
emailHelper.Send();

 

排坑:網絡

一、騰訊企業郵箱,smtp發送服務器是 「smtp.exmail.qq.com」,官方給出的是465,我使用587端口,使用其餘端口發佈到服務器上,我這兒提示超時。具體587與465端口的區別,找到一個歪果仁的貼子本身看吧 https://stackoverflow.com/questions/15796530/what-is-the-difference-between-ports-465-and-587socket

二、網易郵箱,有個很帶勁的操做,」受權密碼「,網易須要本身新增一個「受權碼」(是用於登陸第三方郵件客戶端的專用密碼)函數

 

 

不以物喜,不以己悲。this

加密

相關文章
相關標籤/搜索