asp.net發送E-mail

發送電子郵件也是項目開發當中常常用到的功能,這裏我整理了一個發送電子郵件(帶附件,支持多用戶發送,主送、抄送)的類庫,供你們參考。html

先上兩個實體類,用於封裝成Mail對象。web

/// <summary>  
/// 發送郵件請求  
/// </summary>  
public class MailRequest  
{  
    #region PrivateFields  
  
    /// <summary>  
    /// 文件名  
    /// </summary>  
    private string _fromField;  
  
    /// <summary>  
    /// 返送到  
    /// </summary>  
    private string _toField;  
  
    /// <summary>  
    /// 抄送  
    /// </summary>  
    private string _copyField;  
  
    /// <summary>  
    /// 附件  
    /// </summary>  
    private string _bccField;  
  
    /// <summary>  
    /// 標題  
    /// </summary>  
    private string _subjectField;  
  
    /// <summary>  
    /// 發送人名  
    /// </summary>  
    private string _bodyField;  
  
    /// <summary>  
    /// 類容  
    /// </summary>  
    private MailRequestAttachments[] _attachmentsField;  
 
    #endregion  
  
    /// <summary>  
    /// 發送人,多我的以分號;間隔  
    /// </summary>  
    public string From  
    {  
        get  
        {  
            return this._fromField;  
        }  
  
        set  
        {  
            this._fromField = value;  
        }  
    }  
  
    /// <summary>  
    /// 收件人,多我的以分號;間隔  
    /// </summary>  
    public string To  
    {  
        get  
        {  
            return this._toField;  
        }  
  
        set  
        {  
            this._toField = value;  
        }  
    }  
  
    /// <summary>  
    /// 抄送人,多我的以分號;間隔  
    /// </summary>  
    public string CC  
    {  
        get  
        {  
            return this._copyField;  
        }  
  
        set  
        {  
            this._copyField = value;  
        }  
    }  
  
    /// <summary>  
    /// 祕密抄送人,多我的以分號;間隔  
    /// </summary>  
    public string Bcc  
    {  
        get  
        {  
            return this._bccField;  
        }  
  
        set  
        {  
            this._bccField = value;  
        }  
    }  
  
    /// <summary>  
    /// 主題  
    /// </summary>  
    public string Subject  
    {  
        get  
        {  
            return this._subjectField;  
        }  
  
        set  
        {  
            this._subjectField = value;  
        }  
    }  
  
    /// <summary>  
    /// 內容  
    /// </summary>  
    public string Body  
    {  
        get  
        {  
            return this._bodyField;  
        }  
  
        set  
        {  
            this._bodyField = value;  
        }  
    }  
  
    /// <summary>  
    /// 附件列表  
    /// </summary>  
    public MailRequestAttachments[] Attachments  
    {  
        get  
        {  
            return this._attachmentsField;  
        }  
  
        set  
        {  
            this._attachmentsField = value;  
        }  
    }  
}  
/// <summary>  
/// 發送郵件請求附件  
/// </summary>  
public class MailRequestAttachments  
{  
    #region PrivateFields  
  
    /// <summary>  
    /// 文件名  
    /// </summary>  
    private string _fileNameField;  
  
    /// <summary>  
    /// 文件內容  
    /// </summary>  
    private byte[] _fileDataField;  
 
    #endregion  
  
    /// <summary>  
    /// 文件名  
    /// </summary>  
    public string FileName  
    {  
        get  
        {  
            return this._fileNameField;  
        }  
  
        set  
        {  
            this._fileNameField = value;  
        }  
    }  
  
    /// <summary>  
    /// 文件內容  
    /// </summary>  
    public byte[] FileData  
    {  
        get  
        {  
            return this._fileDataField;  
        }  
  
        set  
        {  
            this._fileDataField = value;  
        }  
    }  
}  

附件的內容很簡單,由於在網絡傳輸當中,是以字節流的形式傳輸的,所以附件的傳輸須要轉換成字節流數組。數組

/// <summary>  
/// 郵件幫助類  
/// </summary>  
public static class MailHelper  
{  
    /// <summary>  
    /// 發送郵件  
    /// </summary>  
    /// <param name="request">郵件內容對象</param>  
    /// <returns>發送郵件所遇到的異常</returns>  
    public static string SendMail(MailRequest request)  
    {  
        try  
        {  
            MailMessage mail = new MailMessage();  
  
            if (string.IsNullOrEmpty(request.From))  
            {  
                request.From = WebConfigurationManager.AppSettings["DefaultMailFrom"];  
            }  
            mail.From = new MailAddress(request.From);  
  
            PaserMailAddress(request.To, mail.To);  
            PaserMailAddress(request.CC, mail.CC);  
            PaserMailAddress(request.Bcc, mail.Bcc);  
  
            mail.Subject = request.Subject;  
            mail.SubjectEncoding = System.Text.Encoding.UTF8;  
            mail.Body = request.Body;  
            mail.ReplyTo = new MailAddress(request.From);  
            mail.IsBodyHtml = true;  
  
            if (request.Attachments != null && request.Attachments.Length > 0)  
            {  
                for (int i = 0; i < request.Attachments.Length; i++)  
                {  
                    Attachment mailAttach = new Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName);  
  
                    mail.Attachments.Add(mailAttach);  
                }  
            }  
  
            if (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVER"]))  
            {  
                throw new ApplicationException("郵件服務無效");  
            }  
  
            //Smtp Server  
            SmtpClient mailClient = new SmtpClient(WebConfigurationManager.AppSettings["SMTPSERVER"]);  
  
            if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]))  
            {  
                //端口號  
                try  
                {  
                    mailClient.Port = Int32.Parse(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]);  
                }  
                catch  
                {  
                    return "SMTP服務器端口設置錯誤,端口必須設置爲數值型";  
                }  
            }  
  
            if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["MAILUSER"]))  
            {  
                mailClient.Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["MAILUSER"], WebConfigurationManager.AppSettings["MAILUSERPW"]);  
                mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;  
            }  
            else  
            {  
                mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;  
            }  
  
            mailClient.Send(mail);  
            mail.Dispose();  
  
            return "郵件發送成功。";  
        }  
        catch (SmtpFailedRecipientsException e)  
        {  
            return e.Message;  
        }  
        catch (SmtpFailedRecipientException e)  
        {  
            return e.Message;  
        }  
        catch (SmtpException e)  
        {  
            return e.Message;  
        }  
        catch (Exception e)  
        {  
            return e.Message;  
        }  
    }  
  
    /// <summary>  
    /// 解析分解郵件地址  
    /// </summary>  
    /// <param name="mailAddress">郵件地址</param>  
    /// <param name="mailCollection">郵件對象</param>  
    private static void PaserMailAddress(string mailAddress, MailAddressCollection mailCollection)  
    {  
        if (string.IsNullOrEmpty(mailAddress))  
        {  
            return;  
        }  
  
        char[] separator = new char[2] { ',', ';' };  
        string[] addressArray = mailAddress.Split(separator);  
  
        foreach (string address in addressArray)  
        {  
            if (address.Trim() == string.Empty)  
            {  
                continue;  
            }  
  
            mailCollection.Add(new MailAddress(address));  
        }  
    }  
  
    /// <summary>  
    /// 字節數組轉換爲流  
    /// </summary>  
    /// <param name="byteArray">字節數組</param>  
    /// <returns>Stream</returns>  
    private static Stream ByteArrayToStream(byte[] byteArray)  
    {  
        MemoryStream mstream = new MemoryStream(byteArray);  
  
        return mstream;  
    }  
}  

這是一個郵件助手類,定義成static,無需實例化,直接類名.方法名的形式調用。安全

只須要上述3個類就能夠實現發送Email了,因爲上面引用的是web.config裏面的信息(asp.net等命名空間,若是是winform等須要本身修改一下),這裏還須要配置一下web.config,以下所示:服務器

<appSettings>  
  <!--郵件發送配置-->  
  <add key="SMTPSERVER" value="smtp.qq.com"/>  
  <!--這是服務器郵箱的地址,若是是新浪,則填 smtp.sina.com-->  
  <add key="MAILUSER" value="xxx"/>  
  <!--注意!這是對應服務器郵箱的帳號-->  
  <add key="MAILUSERPW" value="yyy"/>  
  <!--注意!這是對應服務器郵箱的帳號密碼-->  
</appSettings>  

最後上一個測試方法,在主函數當中或者Page_Load事件中執行便可:網絡

private void SendEmailExample()  
{  
    MailRequest mail = new MailRequest();  
    mail.Subject = "hello,this is a e-mail sent by asp.net mailhelper.";//主題  
    mail.Body = "hello,this is a e-mail sent by asp.net mailhelper.<a href='http://blog.csdn.net/guwei4037'>歡迎訪問個人博客。</a>";//內容  
    mail.Bcc = "512122338@qq.com";//祕密抄送人  
    mail.From = "345822155@qq.com";//發送人  
    mail.CC = "guwei4037@sina.com";//抄送人  
    mail.To = "guwei4037@gmail.com";//收件人  
  
    //讀取文件到bytes  
    FileStream stream = new FileStream(Path.Combine(Server.MapPath("~"), "doc\\test.txt"), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);  
    byte[] bytes = new byte[stream.Length];  
    stream.Read(bytes, 0, bytes.Length);  
    stream.Close();  
  
    //附件  
    MailRequestAttachments attachments = new MailRequestAttachments();  
    attachments.FileName = "test.txt";  
    attachments.FileData = bytes;  
    mail.Attachments = new MailRequestAttachments[] {   
            attachments  
        };  
  
    string sendMainResult = "-1";  
    if (!string.IsNullOrEmpty(mail.CC.Replace(";", "")) && !string.IsNullOrEmpty(mail.To.Replace(";", "")))  
    {  
        sendMainResult = MailHelper.SendMail(mail);  
    }  
    Response.Write(sendMainResult);  
}  

發送郵件成功,附件也能正常打開,並且多個用戶都收到了電子郵件。截圖爲證。app

源代碼下載,請點擊這裏。asp.net

 

———————————————————————————————————————————————————————函數

最近一個朋友問我說,我上面的這段發送郵件的代碼出問題了,出錯截圖以下:測試

心想該不是qq郵箱SMTP設置沒打開吧,打開郵箱一看是打開的。

注意下面的一段舒適提示:登陸第三方客戶端時,密碼框請輸入「受權碼」進行驗證。難道是qq郵箱的安全機制修改過了?

按照提示,發送了短信,收到了受權碼。把原來程序中的發送郵箱帳號的明文密碼修改爲這個受權碼,再在程序中加以下兩行代碼便可。

  mailClient.EnableSsl = true;
  mailClient.UseDefaultCredentials = false;
相關文章
相關標籤/搜索