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

时间:2017-04-20 07:34:32

标签: vb.net nullreferenceexception

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

第一个错误:

enter image description here

第二个错误:

enter image description here

代码:

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

1 个答案:

答案 0 :(得分:4)

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

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

如果您仍有问题,请与我们联系