[ASP.NET] 簡易Mail發送程式

System.Net.Mail是ASP.NET不錯用的Mail處理類別,只是不適合用在Big5編碼上,遇到「奇」、「寶」等特殊字會變亂碼,所以建議還是使用在UTF-8編碼的MailSever上,以下是用System.Net.Mail類別寫出來的簡易Mail發送程式,請參考以下範例:

System.Net.Mail是ASP.NET不錯用的Mail處理類別,只是不適合用在Big5編碼上,遇到「奇」、「寶」等特殊字會變亂碼,所以建議還是使用在UTF-8編碼的MailSever上,以下是用System.Net.Mail類別寫出來的簡易Mail發送程式,請參考以下範例:


MailMessage MMsg = new MailMessage();   //宣告並實體化MailMessage    

                    //宣告並實體化SmtpClient,設定MailServer,Port     
                    SmtpClient smtpClnt = new SmtpClient(MailServer, Port);

                    smtpClnt.Credentials = new System.Net.NetworkCredential(Account, Password);

                    MMsg.From = getEMailAddr(Frm)[0];
                    MMsg.Subject = Subject;
                    MMsg.IsBodyHtml = isBodyHtml;
                    MMsg.SubjectEncoding = Encoding.UTF8;
                    MMsg.BodyEncoding = Encoding.UTF8;

                    MMsg.Body = Body;

                    //處理收件人
                    if (mTo.IndexOf('@') > -1)
                        foreach (MailAddress MA in getEMailAddr(mTo))
                            MMsg.To.Add(MA.Address);
                    //處理副本 
                    if (cc.IndexOf('@') > -1)
                        foreach (MailAddress MA in getEMailAddr(cc))
                            MMsg.CC.Add(MA.Address);
                    //處理密件副本  
                    if (bcc.IndexOf('@') > -1)
                        foreach (MailAddress MA in getEMailAddr(bcc))
                            MMsg.Bcc.Add(MA.Address);

                    //處理附加檔  
                    if (Attachment != null)
                        foreach (string FileName in Attachment.Split(','))
                            MMsg.Attachments.Add(new Attachment(FileName));

                    //送出郵件  
                    smtpClnt.Send(MMsg);

 

完整程式檔案下載:MailSender.zip