发送邮件时未将对象引用设置为对象异常的实例

Object reference not set to an instance of an object exception when sending mail

我在发送电子邮件时遇到了以下问题。我不明白为什么会发生此错误。我无法复制错误,所以我添加了图像。

第一个错误:

第二个错误:

代码:

Imports System.Net.Mail
Public Class Form1
    Private sendMail As MailMessage ' var for Mail
    Private setSmtp As SmtpClient ' var for smrp
    '====== Create mail Sender
    Private Sub mailBox()
        Try
            sendMail.Subject = Trim(subjectTextBox.Text) ' Subject //1st error
            sendMail.From = New MailAddress(Trim(fromTextBox.Text)) ' from
            sendMail.To.Add(Trim(toTextBox.Text)) ' To
            sendMail.IsBodyHtml = False ' if msg html
            sendMail.Body = Trim(msgTextBox.Text) ' mail body
            sendMail.Priority = MailPriority.Normal ' Priority kemn hobe
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub
    '====== Config smtp Server
    Private Sub smtpServer()
        Try
            setSmtp.Credentials = New Net.NetworkCredential(Trim(fromTextBox.Text), "*******") '// 2nd error
            setSmtp.EnableSsl = True
            setSmtp.Host = "smtp.gmail.com"
            setSmtp.Port = "587"
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub
    '====== Send Mail
    Private Sub mailSender()
        Try
            setSmtp.Send(sendMail) ' send mail through created smtp //3rd error
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub
    '======== Send Mail By Button
    Private Sub btnSendMail_Click(sender As Object, e As EventArgs) Handles btnSendMail.Click
        ' ============= Send Mail ===============
        mailBox() ' Call Created mail
        smtpServer() ' Call Created smtp server
        mailSender() ' Call the mailSender Sub
    End Sub
    ' ======= Discard Filed
    Private Sub btnDiscard_Click(sender As Object, e As EventArgs) Handles btnDiscard.Click
        subjectTextBox.Clear()
        fromTextBox.Clear()
        toTextBox.Clear()
        msgTextBox.Clear()
    End Sub
End Class

你得到一个空指针,因为你没有启动你的变量。如果变量未启动,则无法更改其设置。换句话说,它在启动之前是不存在的。

Private sendMail As New MailMessage ' var for Mail
Private setSmtp As New SmtpClient ' var for smrp

如果您仍有问题,请告诉我