邮件尝试对象参考?

时间:2014-03-04 06:04:49

标签: vb.net email smtp nullreferenceexception mailing

我正在尝试制作一个简单的电子邮件发送程序,但当它说object reference not set to an instance of an object

时它让我很困惑
Try
       Dim mail As MailMessage
       Dim client As SmtpClient
       Dim SmtpServer As New SmtpClient()
       Dim fromAddress As String
       Dim toAddress1 As String
       Dim toAddress2 As String
       Dim toAddress3 As String
       Dim subject As String
       Dim message As String
       SmtpServer.Credentials = New Net.NetworkCredential("*********@gmail.com", "**********")
       client.UseDefaultCredentials = False

       fromAddress = FromEmail.Text
       If ToEmail1.Visible = True Then
             toAddress1 = ToEmail1.Text
       ElseIf ToEmail1.Visible = True And ToEmail2.Visible = True Then
             toAddress1 = ToEmail1.Text
             toAddress2 = ToEmail2.Text
       ElseIf ToEmail1.Visible = True And ToEmail2.Visible = True And ToEmail3.Visible = True Then
             toAddress1 = ToEmail1.Text
             toAddress2 = ToEmail2.Text
             toAddress3 = ToEmail3.Text
       End If

       subject = "Subject"
       Message = "Message"

       mail = New MailMessage(fromAddress, toAddress1, subject, Message)
       client = New SmtpClient("Smtp.live.com")

       client.Port = 587
       Dim SMTPUserInfo As New System.Net.NetworkCredential("user@hotmail.com", "password")
       client.Credentials = SMTPUserInfo

        client.Send(mail)
        MsgBox("sent")
Catch ex As Exception
            MsgBox(ex.Message.ToString())
End Try

1 个答案:

答案 0 :(得分:0)

你宣布两个smtpclients

 Dim client As SmtpClient
 Dim SmtpServer As New SmtpClient()

您实例化了SmtpServer,但没有client。然后你做

 client.UseDefaultCredentials = False

我想这是引发异常的地方。 代码看起来像有一些行通过SmtpServer从谷歌帐户和其他行发送一些邮件通过客户端从hotmail帐户发送一些邮件。此外,SmtpServer正在使用config.sys中定义的一些服务器。