0

I am trying to make a simple e-mail sending program but it has confused me when it said 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
Kashish Arora
  • 900
  • 5
  • 25
  • 39
  • Where did the error occur? What is the full text of the error message? Is this WebForms or MVC? Which version of .NET? – Adam Zuckerman Mar 04 '14 at 06:28
  • Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Mar 04 '14 at 06:50

1 Answers1

0

you're declaring two smtpclients

 Dim client As SmtpClient
 Dim SmtpServer As New SmtpClient()

you instantiated SmtpServer, but not client. Then you do

 client.UseDefaultCredentials = False

I guess this is where the exception is raised. the code looks like having some lines to send some mail through SmtpServer from a google account and other lines to send some mail through client from a hotmail account. Besides, SmtpServer is using some server defined in config.sys.

xavigonza
  • 170
  • 1
  • 7