Danno
Danno

Reputation: 19

Sending Email from Visual Basic

I am working on a project and part of this project is to send emails to a list of email addresses located in SQL. I am using the following code, which, when sent, just throws a "Sending Failed" error. Nothing else.

Can anyone please help me out with this one? I would really appreciate it.

       'Connect to SQL Server database and query out only Address column to fill into DataTable

    Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=FigClubs;Integrated Security=True;Pooling=False")

    Dim cmd As SqlCommand = New SqlCommand("SELECT Email FROM Members", con)

    con.Open()

    Dim myDA As SqlDataAdapter = New SqlDataAdapter(cmd)

    Dim myDataTable As DataTable = New DataTable

    myDA.Fill(myDataTable)

    con.Close()

    con = Nothing



    'New a MailMessage instance

    Dim mailMessage As MailMessage = New MailMessage()

    mailMessage.From = New MailAddress(TextBox4.Text.Trim())



    ' Determine the mailMessage.To property based on CheckBox checked status

    If CheckBox1.Checked = True Then

        For Each dr As DataRow In myDataTable.Rows

            mailMessage.To.Add(New MailAddress(dr.Item(0).ToString))

        Next

    Else

        mailMessage.To.Add(New MailAddress(TextBox3.Text.Trim()))

    End If



    mailMessage.Subject = TextBox1.Text.Trim()

    mailMessage.Body = TextBox2.Text.Trim()
    Dim smtpClient As SmtpClient = New SmtpClient("smtp.google.com")
    smtpClient.Port = ("587")
    smtpClient.Credentials = New System.Net.NetworkCredential("HIDDEN", "HIDDEN")
    smtpClient.Send(mailMessage)



    Try

        smtpClient.Send(mailMessage)

    Catch smtpExc As SmtpException

        'Log errors
        MsgBox(smtpExc.Message)
    Catch ex As Exception

        'Log errors
        MsgBox(ex.Message)
    End Try

I got that code from a google search. Any help you can provide to get this working would be so appreciated.

Thanks in advance, Dan

EDIT - Got it to work:

Got it to work using the following. Just in case anyone else needs it:

  Try
    Dim Smtp_Server As New SmtpClient
    Dim e_mail As New MailMessage()
    Smtp_Server.UseDefaultCredentials = False
    Smtp_Server.Credentials = New Net.NetworkCredential("HIDDEN", "HIDDEN")
    Smtp_Server.Port = 587
    Smtp_Server.EnableSsl = True
    Smtp_Server.Host = "smtp.gmail.com"

    e_mail = New MailMessage()
    e_mail.From = New MailAddress(TextBox4.Text)
    e_mail.To.Add(TextBox3.Text)
    e_mail.Subject = TextBox1.Text
    e_mail.IsBodyHtml = False
    e_mail.Body = TextBox2.Text
    Smtp_Server.Send(e_mail)
    MsgBox("Mail Sent")

Catch error_t As Exception
    MsgBox(error_t.ToString)
End Try

Thanks guys. Hope all is well :)

Upvotes: 0

Views: 13060

Answers (1)

Trevor
Trevor

Reputation: 8004

Okay, here's a great solution for you...

Imports System.Net.Mail 'Namespace for sending the email

Public Class Form1 'Whatever class your doing this from...

'I tested with a button click event...
Private Sub btnSendEmail_Click(sender As Object, e As EventArgs) Handles btnSendEmail.Click
    Dim dtEmails As New DataTable
    Dim strEmails() As String = {"[email protected]", "[email protected]"}
    Dim strBuilder As New System.Text.StringBuilder 'Can be used to build a message

    'This was only for my testing...
    dtEmails.Columns.Add("EmailAddress")
    For Each Str As String In strEmails
        dtEmails.Rows.Add(Str)
    Next

    'Loop through our returned datatable and send the emails...'
    If dtEmails.Rows.Count > 0 Then
        strBuilder.AppendLine("Emails Confirmation")
        strBuilder.AppendLine(" ")

        For i As Integer = 0 To dtEmails.Rows.Count - 1 'Whatever your datatbale is called'
            Try
                Dim newMail As New Mail 'Use our new mail class to set our properties for the email'
                newMail.MailMessageTo = dtEmails.Rows(i).Item("EmailAddress") 'What your email address column name is in the data table'
                newMail.MailSubject = "Just a Test email!"
                newMail.MailMessage = "Did you get this email, please let me know!"

                If Mail.SendMail(newMail) Then
                    strBuilder.AppendLine("SENT - " & dtEmails.Rows(i).Item("EmailAddress").ToString.ToUpper)
                Else
                    strBuilder.AppendLine("FAILED - " & dtEmails.Rows(i).Item("EmailAddress").ToString.ToUpper)
                End If

            Catch ex As Exception
                Continue For
            End Try
        Next
    End If

    If strBuilder.Length > 0 Then
        MessageBox.Show(strBuilder.ToString())
    End If
 End Sub

 End Class

 'You can put this class at the bottom of your class your using...This handles the emails...
 Public Class Mail
  Public Property MailMessageTo As String
  Public Property MailMessage As String
  Public Property MailSubject As String

 'This will send your mail...
 Public Shared Function SendMail(ByVal oMail As Mail) As Boolean
    Dim Smtp_Server As New SmtpClient
    Dim e_mail As New MailMessage()

    Try
        Smtp_Server.UseDefaultCredentials = False
        Smtp_Server.Credentials = New Net.NetworkCredential("EMAIL", "PASSWORD")
        Smtp_Server.Port = 587
        Smtp_Server.EnableSsl = True
        Smtp_Server.Host = "smtp.gmail.com"

        e_mail = New MailMessage()
        e_mail.From = New MailAddress("EMAIL") 'Whatever you want here'
        e_mail.To.Add(oMail.MailMessageTo)
        e_mail.Subject = oMail.MailSubject
        e_mail.IsBodyHtml = False
        e_mail.Body = oMail.MailMessage
        Smtp_Server.Send(e_mail)

        Return True
    Catch error_t As Exception
        Return False
    Finally
        Smtp_Server = Nothing
        e_mail = Nothing
    End Try

  End Function

 End Class

This works really well, you can edit as needed to. This is much more organized and easier to maintain for what you would need. Also another good note to remember your looping through a DataTable sending emails, you may want to put some of this on a BackgroundWorker as this can lock up the UI thread... Another thing to check when looping through your DataTable, you may want to check if the email your referencing isn't 'DBNull.value', I didn't check for that, other wise it will throw an exception.

Happy Coding!

Upvotes: 2

Related Questions