ASP.NET 2.0發電子郵件(EMail)的範例

摘要:ASP.NET 2.0發電子郵件的範例

.NET Framework 2.0中對於發送電子郵件的相關程式語法,有新的方式可以使用。

為了未來方便使用,以及未來如果要調整時可以集中調整,小喵寫一個MyMailObj.vb的物件(類別Class),為來需要寄送EMail可以統一的呼叫此物件(類別Class)。這個(類別Class)MyMailObj.vb的相關程式碼如下:

由於有使用EMail與附加檔案的功能,所以記得要Imports兩個NameSpace

Imports System.Net.Mail
Imports System.IO

另外要可以使用物件集合List(Of 物件)的寫法,所以還需要Imports另外一個NameSpace

imports System.Collections.Generic

Imports System.Net.Mail  
Imports System.Collections.Generic 
Imports Microsoft.VisualBasic  
  
Public Class MyMailObj  
    Private m_Frm As MailAddress       '寄件者  
    Private m_mTo As List(Of MailAddress)  '收件者  
    Private m_cc As List(Of MailAddress)   '副本  
    Private m_bcc As List(Of MailAddress)  '密件副本  

    Private m_Attachment As List(Of FileInfo) '附加檔  
    Private m_Body As String = ""       '信件內容  
    Private m_Subject As String = ""    '主旨  
    Private m_isBodyHtml As Boolean = True  '內容格式是否HTML  

    '寄件者  
    Public Property Frm() As MailAddress
        Get
            Return m_Frm
        End Get
        Set(ByVal value As MailAddress)
            m_Frm = value
        End Set
    End Property

    '收件者  
    Public Property mTo() As List(Of MailAddress)
        Get
            Return m_mTo
        End Get
        Set(ByVal value As List(Of MailAddress))
            m_mTo = value
        End Set
    End Property

    '副本  
    Public Property cc() As List(Of MailAddress)
        Get
            Return m_cc
        End Get
        Set(ByVal value As List(Of MailAddress))
            m_cc = value
        End Set
    End Property

    '密件副本  
    Public Property bcc() As List(Of MailAddress)
        Get
            Return m_bcc
        End Get
        Set(ByVal value As List(Of MailAddress))
            m_bcc = value
        End Set
    End Property

    '附加檔  
    Public Property Attachment() As List(Of FileInfo)
        Get
            Return m_Attachment
        End Get
        Set(ByVal value As List(Of FileInfo))
            m_Attachment = value
        End Set
    End Property

    '內容  
    Public Property Body() As String
        Get
            Return m_Body
        End Get
        Set(ByVal value As String)
            m_Body = value
        End Set
    End Property

    '主旨  
    Public Property Subject() As String
        Get
            Return m_Subject
        End Get
        Set(ByVal value As String)
            m_Subject = value
        End Set
    End Property

    '內容格式是否HTML  
    Public Property isBodyHtml() As Boolean
        Get
            Return m_isBodyHtml
        End Get
        Set(ByVal value As Boolean)
            m_isBodyHtml = value
        End Set
    End Property

    Private Function ChkData() As String
        Try
            Dim Rc As String = ""
            If m_Frm Is Nothing Then
                Rc += "無寄件者"
            End If
            If m_mTo Is Nothing And m_cc Is Nothing And m_bcc Is Nothing Then
                Rc += "無收件者"
            End If
            If m_Subject Is Nothing Then
                Rc += "無主旨"
            Else
                If m_Subject.Trim() = "" Then
                    Rc += "無主指"
                End If
            End If
            If m_Body Is Nothing Then
                Rc += "無內容"
            Else
                If m_Body.Trim() = "" Then
                    Rc += "無內容"
                End If
            End If
            If Rc = "" Then
                Rc = "Success"
            End If
            Return Rc

        Catch ex As Exception
            Throw
        End Try
    End Function

    Public Function SendMail() As String
        Try
            '檢查必要項目  
            Dim chkRc As String = ChkData()
            If chkRc <> "Success" Then
                Throw New Exception(chkRc)
            Else

                Dim MMsg As New MailMessage '宣告並實體化MailMessage     
                Dim y As Integer            '宣告整數     

                '宣告並實體化SmtpClient,設定MailServer,Port     
                Dim smtpClnt As New SmtpClient("mail.panasonic.com.tw", "25") '請更改為自己的MailServer     

                MMsg.From = m_Frm  '設定寄件者     
                MMsg.Subject = m_Subject  '設定主旨     
                MMsg.IsBodyHtml = m_isBodyHtml    '設定內容是否為HTML格式     
                MMsg.SubjectEncoding = Encoding.UTF8    '主旨指定用UTF-8格式
                MMsg.BodyEncoding = Encoding.UTF8   '內容指定用UTF-8格式

                Dim tBody As String
                If isBodyHtml Then  '如果是HTML格式     
                    'Body = Replace(Body, vbCrLf, "")    '取代換行     
                    '信件內容控制     
                    tBody = ".dl{font-size:14}" + m_Body + ""
                Else    '非HTML格式     
                    tBody = m_Body
                End If
                '設定Message信件內容     
                MMsg.Body = tBody

                '處理收件者  
                If m_mTo IsNot Nothing Then
                    If m_mTo.Count > 0 Then
                        For y = 0 To m_mTo.Count - 1
                            MMsg.To.Add(m_mTo.Item(y))
                        Next
                    End If
                End If

                '處理副本  
                If m_cc IsNot Nothing Then
                    If m_cc.Count > 0 Then
                        For y = 0 To m_cc.Count - 1
                            MMsg.CC.Add(m_cc.Item(y))
                        Next
                    End If
                End If

                '處理密件副本  
                If m_bcc IsNot Nothing Then
                    If m_bcc.Count > 0 Then
                        For y = 0 To m_bcc.Count - 1
                            MMsg.Bcc.Add(m_bcc.Item(y))
                        Next
                    End If
                End If

                '處理附加檔  
                If m_Attachment IsNot Nothing Then
                    If m_Attachment.Count > 0 Then
                        Dim matt As Attachment
                        For y = 0 To m_Attachment.Count - 1
                            matt = New Attachment(m_Attachment.Item(y).FullName)
                            MMsg.Attachments.Add(matt)
                        Next
                    End If
                End If

                '送出郵件  
                smtpClnt.Send(MMsg)
                Return "Success"
            End If


        Catch ex As Exception
            Throw New Exception(ex.Message)

        End Try
    End Function
  
End Class

接著來測試一下如何使用這個MyMailObj寄信

小喵在Default.aspx中,安排畫面如下:

收件者:<asp:TextBox ID="txtTo" runat="server" Width="494px"></asp:TextBox><br /> 
副本:<asp:TextBox ID="txtCC" runat="server" Width="508px"></asp:TextBox><br /> 
密件副本:<asp:TextBox ID="txtBCC" runat="server" Width="474px"></asp:TextBox><br /> 
主旨:<asp:TextBox ID="txtSubject" runat="server" Width="508px"></asp:TextBox> 
	<br /> 
	HTML內容:<asp:CheckBox ID="chkisBodyHTML" runat="server" /> 
	<br /> 
內容:<asp:TextBox ID="txtContent" runat="server" Width="508px" Height="163px"  
		TextMode="MultiLine"></asp:TextBox> 
	<br /> 
	<asp:Button ID="btnSend" runat="server" Text="送信" />

◎ASP.NET 2.0 防止Script攻擊機制:

ASP.NET 2.0預設有防止Script攻擊的機制,所以當畫面中有設定一個MutiLine的控制項時,而內容又有輸入一些html的符號時,此機制就會啟動並且顯示如下的錯誤

A potentially dangerous Request.Form value was detected from the client (txtBody="...sp.net 2.0<br>
這是一封測試信,測試ASP....").

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.
Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (txtBody="...sp.net 2.0<br>

 

因此如果要讓使用者可以輸入html的語法,就必須把這一頁的這個檢查關閉,請在<%Page%>中設定【ValidateRequest="false"】即可

 

◎寄件者名稱、收件者名稱處理:

收發電子郵件只需要有EMail Address就可以了,但是如果希望使用者收到的時候也能夠顯示名稱,那麼小喵特別設定一個規則,如果就是EMail Address後用()來放名稱

例如:topcat@blueshop.com.tw(小喵)

當然送入的時候必須要先處理一下這樣的內容,將之變成List(Of MailAddress),才能符合MyMailObj中的方式

	'信件格式:傳入字串MAddrs包含數個Email含EMail名稱,每個EMail以;區分,格式如以下範例: 
	'格式:EMailAddress(EMailName) 
	'範例:topcat@blueshop.com.tw(小喵BlueShop);topcat@yahoo.com.tw(小喵Yahoo) 

	Try 

		Dim RcMail As List(Of MailAddress) 
		Dim tMAddr As String = "" 
		Dim tMName As String = "" 
		Dim y As Integer 
		Dim tMail As MailAddress 

		If MAddrs <> "" Then 
			'如果傳入有資料 
			RcMail = New List(Of MailAddress) 
			If InStr(1, MAddrs, ";", CompareMethod.Text) = 0 Then 
				'判斷只有一組Mail 
				If InStr(1, MAddrs, "(", CompareMethod.Text) > 0 Then 
					'有Mail_Name 
					tMAddr = MAddrs.Split("(")(0)   'Mail_Addr 
					tMName = Replace(MAddrs.Split("(")(1), ")", "") 'MailName 
				Else 
					tMAddr = MAddrs 'Mail_Addr 

				End If 
				tMail = New MailAddress(tMAddr, tMName) 
				RcMail.Add(tMail) 
			Else 
				'多組Mail處理 
				Dim sMAddrs() As String '每組Mail含名字處理 
				sMAddrs = MAddrs.Split(";") 
				For y = 0 To sMAddrs.Length - 1 
					'判斷是否有名稱 
					If InStr(1, sMAddrs(y), "(", CompareMethod.Text) > 0 Then 
						'有名稱處理 
						tMAddr = sMAddrs(y).Split("(")(0) 
						tMName = Replace(sMAddrs(y).Split("(")(1), ")", "") 

					Else 
						'無名稱處理 
						tMAddr = sMAddrs(y) 
						tMName = "" 
					End If 
					tMail = New MailAddress(tMAddr, tMName) 
					RcMail.Add(tMail) 
				Next 
			End If 
		End If 
		Return RcMail 

	Catch ex As Exception 
		Throw New Exception(ex.Message) 

	End Try 
End Function

最後就是發信按鈕按下後的程式碼:

Protected Sub btnSendMail_Click(sender As Object, e As EventArgs) Handles btnSendMail.Click
	Try 
		Dim oMail As New MyMailObj 
		Dim Frm As List(Of MailAddress) = GetEMailAddr(Me.txtFrm.Text) 

		If Frm.Count > 0 Then 
			oMail.Frm = Frm.Item(0) 
		Else 
			Response.Write("無寄件者") 
			Exit Sub 
		End If 


		Dim mTo As List(Of MailAddress) = GetEMailAddr(Me.txtTo.Text) 
		oMail.mTo = mTo 

		Dim CC As List(Of MailAddress) = GetEMailAddr(Me.txtCC.Text) 
		oMail.cc = CC 

		Dim BCC As List(Of MailAddress) = GetEMailAddr(Me.txtBCC.Text) 
		oMail.bcc = BCC 

		Dim Subject As String = Me.txtSubject.Text 
		Dim mBody As String = Me.txtContent.Text 
		Dim isBodyHtml As Boolean = Me.chkisBodyHTML.Checked 

		oMail.Subject = Subject 
		oMail.Body = mBody 
		oMail.isBodyHtml = isBodyHtml 

		Dim rc As String = oMail.SendMail() 
		If rc = "Success" Then 
			Response.Write("送信成功!!") 
		End If 


	Catch ex As Exception 
		Response.Write(ex.Message) 
	End Try 

End Sub

以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat