0

I'm facing the following problems when sending an email. I don't understand why this error happens. I can't copy the error so I have added images.

First error:

enter image description here

Second error:

enter image description here

Code:

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
Bugs
  • 4,356
  • 9
  • 30
  • 39

1 Answers1

4

You get a nullpointer because you don't initiate your variables. You cannot change settings of a variable if it isn't initiated. In other words, it doesnt exist before initiated.

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

If you still have issues let me know

Zulatin
  • 253
  • 1
  • 3
  • 14
  • 1
    @MuhammadImran you need the keyword `New`. That's the difference and by not using `New`, when you come to assign any properties on `sendMail` or `setSmtp`, it will fail. – Bugs Apr 20 '17 at 08:15
  • Thank you! i understand now and problem solved. – Muhammad Imran Apr 20 '17 at 08:33