0

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 :)

Danno
  • 19
  • 2
  • 3
  • 9
  • Posting [self-answers](http://stackoverflow.com/help/self-answer) is encouraged here , but please do it properly. Add an actual answer to your own question (in the "Your Answer" space below) instead of editing it in to your question. You can even accept the answer as being correct; you won't gain any reputation by doing so, but you can earn reputation by getting upvotes on that answer. – Ken White Apr 02 '14 at 14:55
  • Hi Ken. I was going to post an actual answer but then a message popped up advising I should just edit my original post lol Anyways, I still have an issue. It appears the above code is only adding one email address to the "To:" field. – Danno Apr 03 '14 at 09:37
  • Hi. Can anyone help with this since I am not allowed to ask in a new thread? – Danno Apr 04 '14 at 01:30
  • Help with *what*, exactly? You've edited your question to mark it as "{RESOLVED}" (in all CAPS for emphasis). No message "pops up" when you try to post an answer in the "Your Answer" section of the page saying you should edit the original question instead. If it does, either you're not posting in the "Your Answer" section, or you've discovered a bug you should post on [meta] (including a screen capture of the page with that error displayed that shows what you're doing at the time, and steps to reproduce it). – Ken White Apr 04 '14 at 01:34
  • You can also ask a new question, if it's a *new question*. You can't simply ask this one again. Make sure you phrase it as a new question, and only provide the code there that's relevant to that new question. – Ken White Apr 04 '14 at 01:36
  • Exactly Ken, just got done explaining this to him. – Trevor Apr 04 '14 at 01:40
  • Sorry guys.Mr CoDeXer, as mentioned in the other thread, The above code works fine and retrieves an email address from the "Email" field in my Database and displays that address in the EmailTextBox in the form and also sends an email message. However, it does not grab any other email addresses from the database. Just that one. I am aware I need to do a loop of some sort but have no idea how. I have searched all over the place since late last night (about 12 hours now) for a solution but can't find one. Can someone please help? I'll buy you beer. – Danno Apr 04 '14 at 01:46
  • Also, sorry for going off in the other thread. Just frustrated. :) – Danno Apr 04 '14 at 01:47
  • I will be posting a solution for you here shortly... – Trevor Apr 04 '14 at 03:10

1 Answers1

2

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 = {"testing@yahoo.com", "testing@gmail.com"}
    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!

Trevor
  • 7,777
  • 6
  • 31
  • 50
  • Thank you Mr CoDeXeR. I haven't gotten it to work yet. On one part you have this: For i As Integer = 0 To dtEmails.Rows.Count - 1 'Whatever your datatbale is called' - Does this indicate that I must change dtEmails to my DataTable name? Sorry for being stupid but where do I get this? :/ – Danno Apr 04 '14 at 04:51
  • Correct, whatever your table is. – Trevor Apr 04 '14 at 05:01
  • Thank you. I feel dumb lol. I will play around with it and once it works for me I will update here. Haven't been able to send an email yet anyway. – Danno Apr 04 '14 at 05:04
  • You will, this works great and it's tried and tested. – Trevor Apr 04 '14 at 05:05
  • i love you. haha Thank you mate. Again, I am sorry for being a dick. Works perfectly now. :) – Danno Apr 04 '14 at 05:19
  • Your welcome,don't forget to vote and Mark as answered. – Trevor Apr 04 '14 at 10:57