⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frmmain.vb

📁 VB.NET - NET Framework - How-To Send Mai VB.NET 发送邮件的示例代码
💻 VB
📖 第 1 页 / 共 5 页
字号:
    ' validators fire and the Form will not close.
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_SYSCOMMAND Then
            If m.WParam.ToInt32 = SC_CLOSE Then
                ' Turn off validation for all controls with CausesValidation = True or else
                ' you will not be able to close the Form until valid data is entered.
                txtTo.CausesValidation = False
                txtFrom.CausesValidation = False
            End If
        End If

        ' Pass other messages on to the original WndProc.
        MyBase.WndProc(m)
    End Sub

    ' Handles the Browse button click event. Uses an OpenFileDialog to allow the 
    ' user to find an attachment to send, which is then added to an arraylist of
    ' MailAttachment objects.
    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        With odlgAttachment
            .InitialDirectory = "C:\"
            .Filter = "All Files (*.*)|*.*|HTML Files (*.htm;*.html)|*.htm|Microsoft Mail Documents (*.msg)|*.msg|Word Documents (*.doc)|*.doc|Excel Files(*.xl*)|*.xl*|Excel Worksheets (*.xls)|*.xls|Excel Charts (*.xlc)|*.xlc|PowerPoint Presentations (*.ppt)|*.ppt|Text Files (*.txt)|*.txt"
            .FilterIndex = 1

            ' The OpenFileDialog control only has an Open button, not an OK button.
            ' However, there is no DialogResult.Open enum so use DialogResult.OK.
            If .ShowDialog() = DialogResult.OK Then
                If IsNothing(arlAttachments) Then
                    arlAttachments = New ArrayList()

                    ' Clear the "(No Attachments)" default text in the ListView
                    lstAttachments.Items.Clear()
                End If
                arlAttachments.Add(New MailAttachment(.FileName))

                ' You only want to show the file name. The OpenFileDialog.FileName
                ' property contains the full path. So Split the path and reverse it
                ' to grab the first string in the array, which is just the FileName.
                Dim strFileName() As String = .FileName.Split(New Char() {CChar("\")})
                strFileName.Reverse(strFileName)
                lstAttachments.Items.Add(strFileName(0))
            End If
        End With
    End Sub

    ' Handles the Send button click event. This routine checks for valid email
    ' addresses, builds the body of a message using StringBuilder, creates a 
    ' mail message, and then attempts to send it.
    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
        ' Perform validation on the To and From email address fields, which are
        ' both required for sending an email.
        Try
            ValidateEmailAddress(txtFrom)
        Catch ex As Exception
            txtFrom.Select(0, txtFrom.Text.Length)

            ' Set the ErrorProvider error with the text to display. 
            erpEmailAddresses.SetError(txtFrom, ex.Message)
            Exit Sub
        End Try

        Try
            ValidateEmailAddress(txtTo)
        Catch exp As Exception
            txtTo.Select(0, txtTo.Text.Length)

            ' Set the ErrorProvider error with the text to display. 
            erpEmailAddresses.SetError(txtTo, exp.Message)
            Exit Sub
        End Try

        ' Use the StringBuilder class instead of traditional string concatenation.
        ' It is optimized for building strings because it is capable of modifying
        ' the underlying buffer instead of having to make a copy of the string for 
        ' each concatenation. Consult the SDK documentation for more information on 
        ' this new class.
        Dim sb As New StringBuilder()

        ' Build the email message body.
        sb.Append("The following email was sent to you from the Send Mail How-To " & _
            "sample application:")
        sb.Append(vbCrLf)
        sb.Append(vbCrLf)
        sb.Append("SUBJECT: ")
        sb.Append(Trim(txtSubject.Text))
        sb.Append(vbCrLf)
        sb.Append(vbCrLf)
        sb.Append("MESSAGE: ")
        sb.Append(Trim(txtBody.Text))
        sb.Append(vbCrLf)

        ' Creating a mail message is as simple as instantiating a class and 
        ' setting a few properties.
        Dim mailMsg As New MailMessage()
        With mailMsg
            .From = txtFrom.Text.Trim
            .To = txtTo.Text.Trim
            .Cc = txtCC.Text.Trim
            .Bcc = txtBCC.Text.Trim
            .Subject = txtSubject.Text.Trim
            .Body = sb.ToString
            .Priority = CType(cboPriority.SelectedIndex, MailPriority)

            If Not IsNothing(arlAttachments) Then
                Dim mailAttachment As Object
                For Each mailAttachment In arlAttachments
                    .Attachments.Add(mailAttachment)
                Next
            End If
        End With

        ' Set the SmtpServer name. This can be any of the following depending on
        ' your local security settings:

        ' a) Local IP Address (assuming your local machine's SMTP server has the 
        ' right to send messages through a local firewall (if present).

        ' b) 127.0.0.1 the loopback of the local machine.

        ' c) "smarthost" or the name or the IP address of the exchange server you 
        ' utilize for messaging. This is usually what is needed if you are behind
        ' a corporate firewall.

        ' See the Readme file for more information.
        SmtpMail.SmtpServer = "smarthost"

        ' Use structured error handling to attempt to send the email message and 
        ' provide feedback to the user about the success or failure of their 
        ' attempt.
        Try
            SmtpMail.Send(mailMsg)
            lstAttachments.Items.Clear()
            lstAttachments.Items.Add("(No Attachments)")

            MessageBox.Show("Your email has been successfully sent!", _
                "Email Send Status", MessageBoxButtons.OK, _
                MessageBoxIcon.Information)
        Catch exp As Exception
            MessageBox.Show("The following problem occurred when attempting to " & _
                "send your email: " & exp.Message, _
                Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    ' Handles the event fired when the control is validated.
    Private Sub emailAddresses_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFrom.Validated, txtTo.Validated
        ' Clear the ErrorProvider of errors.
        erpEmailAddresses.SetError(CType(sender, TextBox), "")
    End Sub

    ' Handles the event fired when the control starts validating. Cast the sender 
    ' instead of hardcoding the ID of the TextBox (e.g., "txtFrom") undergoing 
    ' validation so that a single routine can handle the validating event for 
    ' more than one TextBox control.
    Private Sub emailAddresses_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtFrom.Validating, txtTo.Validating
        Dim txt As TextBox = CType(sender, TextBox)

        Try
            ValidateEmailAddress(txt)
        Catch exp As Exception
            ' Cancel the event and highlight the text to be corrected by the user.
            e.Cancel = True
            txt.Select(0, txt.Text.Length)

            ' Set the ErrorProvider error with the text to display. 
            erpEmailAddresses.SetError(txt, exp.Message)
        End Try
    End Sub

    ' Handles the form Load event. Checks to make sure that the SMTP Service is 
    ' both installed and running.
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Ensure the SMTP Service is installed.
        Dim services() As ServiceController = ServiceController.GetServices
        Dim service As ServiceController
        Dim blnHasSmtpService As Boolean = False

        ' Loop through all the services on the machine and find the SMTP Service.
        For Each service In services
            If service.ServiceName.ToLower = "smtpsvc" Then
                blnHasSmtpService = True
                Exit For
            End If
        Next

      

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -