Support Forums
[Source] My Gmail Email Sender - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Visual Basic and the .NET Framework (https://www.supportforums.net/forumdisplay.php?fid=19)
+---- Thread: [Source] My Gmail Email Sender (/showthread.php?tid=18699)



[Source] My Gmail Email Sender - euverve - 05-12-2011

Features:
1. Multi sender's email separated by a semi-colon with same password.
2. Multi recipient (targets in TO, CC, BCC) separated by a semi-colon
3. Html format and email priorities
4. Email bomber and send by amount only
5. With multiple attachments

[Image: 13362915835160650751150.jpg]

Code:
Imports System.Net.Mail
Imports System.ComponentModel

Public Class EmailSender
    Dim html As Boolean
    Dim priority As String
    Dim SendAmount As Integer

    Private Sub ButtonSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSend.Click

        Try
            ' Clear tooltips
            ErrorProvider1.Clear()
            TextBoxSentMails.Text = "0"

            If ButtonSend.Text = "Cancel" Then
                Me.BackgroundWorker1.CancelAsync()
                enablegroupboxes()
                ButtonSend.Text = "Send"
            Else
                'Validate Email Address
                ValidateEmail()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Validation Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub ButtonClearData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonClearData.Click
        Try
            TxtSenderUsername.Clear()
            TxtSenderPassword.Clear()
            TxtRecipientEmail.Clear()
            TxtEmailSubject.Clear()
            EmailMessage.Clear()
            ListBoxAttachmentsFiles.Items.Clear()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Clear Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub ButtonRemoveFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonRemoveFiles.Click
        If ListBoxAttachmentsFiles.SelectedIndex > -1 Then
            ListBoxAttachmentsFiles.Items.RemoveAt(ListBoxAttachmentsFiles.SelectedIndex)
        End If
    End Sub

    Private Sub ButtonAttach_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonAttach.Click
        Try
            Dim Counter As Integer

            OFD.Title = "Select the file(s) to attach"
            OFD.ShowDialog()

            For Counter = 0 To UBound(OFD.FileNames)
                ListBoxAttachmentsFiles.Items.Add(OFD.FileNames(Counter))
            Next

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try

    End Sub

    Sub ValidateEmail()
        Try
            ' The regular expression rule
            Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")

            ' If the email matches the regular expression
            If CheckBox1.CheckState = 1 And CheckBox2.CheckState = 1 Then
                If Expression.IsMatch(TxtSenderUsername.Text) And _
                    Expression.IsMatch(TxtRecipientEmail.Text) And _
                    Expression.IsMatch(TxtRecipientCCEmail.Text) And _
                    Expression.IsMatch(TxtRecipientBCCEmail.Text) Then
                    'Send Email Message
                    If TxtSenderUsername.Text.Contains("@gmail.com") = False Then
                        MsgBox("You need to have a valid gmail address!" + vbNewLine + "Example: username@gmail.com")
                        ErrorProvider1.SetError(TxtSenderUsername, " Please enter your email.")
                        Exit Sub
                    Else
                        If TxtSenderPassword.Text = "" Then
                            MsgBox("You forgot your password!")
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        ElseIf TxtSenderPassword.Text.Length <= 7 Then
                            MessageBox.Show("Minimum Gmail password length is 8 characters!" & vbNewLine & "Please correct this error!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        Else
                            SendEmail()
                        End If
                    End If
                Else
                    'Show error
                    erroremail()
                End If
            ElseIf CheckBox1.CheckState = 0 And CheckBox2.CheckState = 1 Then
                If Expression.IsMatch(TxtSenderUsername.Text) And _
                    Expression.IsMatch(TxtRecipientEmail.Text) And _
                    Expression.IsMatch(TxtRecipientBCCEmail.Text) Then
                    'Send Email Message
                    If TxtSenderUsername.Text.Contains("@gmail.com") = False Then
                        MsgBox("You need to have a valid gmail address!" + vbNewLine + "Example: username@gmail.com")
                        ErrorProvider1.SetError(TxtSenderUsername, " Please enter your email.")
                        Exit Sub
                    Else
                        If TxtSenderPassword.Text = "" Then
                            MsgBox("You forgot your password!")
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        ElseIf TxtSenderPassword.Text.Length <= 7 Then
                            MessageBox.Show("Minimum Gmail password length is 8 characters!" & vbNewLine & "Please correct this error!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        Else
                            SendEmail()
                        End If
                    End If
                Else
                    'Show error
                    erroremail()
                End If
            ElseIf CheckBox1.CheckState = 1 And CheckBox2.CheckState = 0 Then
                If Expression.IsMatch(TxtSenderUsername.Text) And _
                    Expression.IsMatch(TxtRecipientEmail.Text) And _
                    Expression.IsMatch(TxtRecipientCCEmail.Text) Then
                    'Send Email Message
                    If TxtSenderUsername.Text.Contains("@gmail.com") = False Then
                        MsgBox("You need to have a valid gmail address!" + vbNewLine + "Example: username@gmail.com")
                        ErrorProvider1.SetError(TxtSenderUsername, " Please enter your email.")
                        Exit Sub
                    Else
                        If TxtSenderPassword.Text = "" Then
                            MsgBox("You forgot your password!")
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        ElseIf TxtSenderPassword.Text.Length <= 7 Then
                            MessageBox.Show("Minimum Gmail password length is 8 characters!" & vbNewLine & "Please correct this error!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        Else
                            SendEmail()
                        End If
                    End If
                Else
                    'Show error
                    erroremail()
                End If
            ElseIf CheckBox1.CheckState = 0 And CheckBox2.CheckState = 0 Then
                If Expression.IsMatch(TxtSenderUsername.Text) And _
                    Expression.IsMatch(TxtRecipientEmail.Text) Then
                    'Send Email Message
                    If TxtSenderUsername.Text.Contains("@gmail.com") = False Then
                        MsgBox("You need to have a valid gmail address!" + vbNewLine + "Example: username@gmail.com")
                        ErrorProvider1.SetError(TxtSenderUsername, " Please enter your email.")
                        Exit Sub
                    Else
                        If TxtSenderPassword.Text = "" Then
                            MsgBox("You forgot your password!")
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        ElseIf TxtSenderPassword.Text.Length <= 7 Then
                            MessageBox.Show("Minimum Gmail password length is 8 characters!" & vbNewLine & "Please correct this error!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            ErrorProvider1.SetError(TxtSenderPassword, " Please enter your password.")
                            Exit Sub
                        Else
                            SendEmail()
                        End If
                    End If
                Else
                    'Show error
                    erroremail()
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try
    End Sub

    Sub SendEmail()
        Try
            ' Bomber
            If RadioButton4.Checked = True Then
                If ButtonSend.Text = "Send" Then
                    Me.BackgroundWorker1.RunWorkerAsync()
                    TextBoxSentMails.Text = "0"
                    disablegroupboxes()
                    ButtonSend.Text = "Cancel"
                Else
                    Me.BackgroundWorker1.CancelAsync()
                    enablegroupboxes()
                    ButtonSend.Text = "Send"
                End If
                ' Amount of mail
            ElseIf RadioButton5.Checked = True Then
                If NumericUpDown1.Value <= "0" Then
                    MessageBox.Show("Input amount of emails to send.", "Email Error", MessageBoxButtons.OK, _
                       MessageBoxIcon.Stop)
                Else
                    If ButtonSend.Text = "Send" Then
                        Me.BackgroundWorker1.RunWorkerAsync()
                        TextBoxSentMails.Text = "0"
                        disablegroupboxes()
                        ButtonSend.Text = "Cancel"
                    Else
                        Me.BackgroundWorker1.CancelAsync()
                        enablegroupboxes()
                        ButtonSend.Text = "Send"
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Sub disablegroupboxes()
        Try
            GroupBoxSender.Enabled = False
            GroupBoxRecipient.Enabled = False
            GroupBoxMessage.Enabled = False
            GroupBoxMailOptions.Enabled = False
            GroupBoxMessageOptions.Enabled = False
            ButtonClearData.Enabled = False
            ButtonSend.Text = "Cancel"
            ' Clear tooltips
            ErrorProvider1.Clear()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Sub enablegroupboxes()
        Try
            GroupBoxSender.Enabled = True
            GroupBoxRecipient.Enabled = True
            GroupBoxMessage.Enabled = True
            GroupBoxMailOptions.Enabled = True
            GroupBoxMessageOptions.Enabled = True
            ButtonClearData.Enabled = True
            ButtonSend.Text = "Send"
            ' Clear tooltips
            ErrorProvider1.Clear()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        Try
            If CheckBox1.CheckState = 1 Then
                TxtRecipientCCEmail.Enabled = True
                TxtRecipientCCEmail.Clear()
                CheckBox1.Text = "Disable"
            Else
                TxtRecipientCCEmail.Enabled = False
                TxtRecipientCCEmail.Text = "*** Not Used ***"
                CheckBox1.Text = "Enable"
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub CheckBox2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox2.CheckedChanged
        Try
            If CheckBox2.CheckState = 1 Then
                TxtRecipientBCCEmail.Enabled = True
                TxtRecipientBCCEmail.Clear()
                CheckBox2.Text = "Disable"
            Else
                TxtRecipientBCCEmail.Enabled = False
                TxtRecipientBCCEmail.Text = "*** Not Used ***"
                CheckBox2.Text = "Enable"
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub RadioButton5_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton5.CheckedChanged
        Try
            If RadioButton5.Checked = True Then
                NumericUpDown1.Enabled = True
            Else
                NumericUpDown1.Enabled = False
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Try
            Dim StartDateTime

            StartDateTime = DateTime.Now()

            Dim smtpServer As New SmtpClient()
            Dim mail As New MailMessage()
            Dim Counter As Integer = 0      'For Attachment
            Dim Attachment As System.Net.Mail.Attachment

            'Username & Password to connect Gmail
            Dim EmailsSenter As String = Trim(TxtSenderUsername.Text)
            Dim sitessenter As String() = Nothing
            sitessenter = EmailsSenter.Split(";")
            Dim aemail As String
            For Each aemail In sitessenter
                smtpServer.Credentials = New Net.NetworkCredential(aemail, TxtSenderPassword.Text)
            Next aemail

            'Single emailer
            'smtpServer.Credentials = New Net.NetworkCredential(TxtSenderUsername.Text, TxtSenderPassword.Text)

            'Check Priorities
            If RadioButton1.Checked = True Then
                mail.Priority = MailPriority.Low
            ElseIf RadioButton2.Checked = True Then
                mail.Priority = MailPriority.Normal
            ElseIf RadioButton3.Checked = True Then
                mail.Priority = MailPriority.High
            End If

            If CheckBox3.Checked = True Then
                html = True
            Else
                html = False
            End If

            ' Html format?
            mail.IsBodyHtml = html

            ' GMAIL Default Port
            smtpServer.Port = 587

            ' GMAIL Smtp
            smtpServer.Host = "smtp.gmail.com"

            ' Enable SSL Check
            smtpServer.EnableSsl = True 'SSL Check
            mail = New MailMessage()

            'Set the content
            mail.From = New MailAddress("Anonymous@Sender.com")

            'multi recipients
            Dim EmailsTo As String = Trim(TxtRecipientEmail.Text)
            Dim sitesto As String() = Nothing
            sitesto = EmailsTo.Split(";")
            Dim s As String
            For Each s In sitesto
                mail.To.Add(s)
            Next s

            'mail.To.Add(TxtRecipientEmail.Text)
            mail.Subject = TxtEmailSubject.Text
            mail.Body = EmailMessage.Text

            If TxtRecipientCCEmail.Enabled = True Then
                ' Multi CC
                Dim EmailsCC As String = Trim(TxtRecipientCCEmail.Text)
                Dim sitesCC As String() = Nothing
                sitesCC = EmailsCC.Split(";")
                Dim scc As String
                For Each scc In sitesCC
                    mail.CC.Add(scc)
                Next scc
            End If
            If TxtRecipientBCCEmail.Enabled = True Then
                ' Multi BCC
                Dim EmailsBCC As String = Trim(TxtRecipientBCCEmail.Text)
                Dim sitesBCC As String() = Nothing
                sitesBCC = EmailsBCC.Split(";")
                Dim sbcc As String
                For Each sbcc In sitesBCC
                    mail.Bcc.Add(sbcc)
                Next sbcc
            End If

            'Set attachment
            For Counter = 0 To ListBoxAttachmentsFiles.Items.Count - 1
                Attachment = New Attachment(ListBoxAttachmentsFiles.Items(Counter).ToString)
                mail.Attachments.Add(Attachment)
            Next

            ' Loop
            Dim intCount As Integer
            Dim amount As Integer = NumericUpDown1.Text - 1

            If RadioButton4.Checked = True Then
                ' Bomber Enabled
                Do Until BackgroundWorker1.CancellationPending
                    smtpServer.Send(mail)

                    SendAmount += 1
                    BackgroundWorker1.ReportProgress(0)
                Loop
            ElseIf RadioButton5.Checked = True Then
                'Send Amount of Emails
                For intCount = 0 To amount
                    If BackgroundWorker1.CancellationPending Then
                        Exit Sub
                    End If
                    smtpServer.Send(mail)

                    SendAmount += 1
                    BackgroundWorker1.ReportProgress(0)
                Next intCount
            End If

            'Message sent status
            Dim Lapse As String
            Lapse = DateDiff(DateInterval.Second, Now, StartDateTime)
            MsgBox(TextBoxSentMails.Text & " email messages is successfully delivered to : " & TxtRecipientEmail.Text & " in " & Lapse & " seconds.")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Stop)
        End Try
    End Sub

    Sub report() Handles BackgroundWorker1.ProgressChanged
        Try
            TextBoxSentMails.Text = SendAmount
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        Try
            If e.Cancelled = True Then
                MsgBox("Email progress is canceled!")
            ElseIf e.Error IsNot Nothing Then
                MsgBox(e.Error.Message)
            Else
                enablegroupboxes()
            End If
            enablegroupboxes()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub Buttonclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Buttonclose.Click
        Dim response As MsgBoxResult
        response = MsgBox("Are you sure you want to close this application?", _
                          vbYesNo + vbExclamation + vbApplicationModal + _
                          vbDefaultButton2, "Close confirmation")
        If response = MsgBoxResult.Yes Then
            'in case the process is still running when the form is about to be closed.
            If BackgroundWorker1.IsBusy Then
                BackgroundWorker1.CancelAsync()
            End If
            ' Messagebox
            aboutbox()

            Me.Visible = False
            Me.Dispose()
            Me.Close()
            End
        ElseIf response = MsgBoxResult.No Then
            Exit Sub
        End If
    End Sub

    Private Sub EmailSender_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Dim tool As New ToolTip()

            tool.SetToolTip(TxtSenderUsername, "Input your email(s).")
            tool.SetToolTip(TxtSenderPassword, "Input your password.")
            tool.SetToolTip(TxtRecipientEmail, "Input your target email(s).")

            tool.SetToolTip(TxtRecipientCCEmail, "Input your CC email(s).")
            tool.SetToolTip(TxtRecipientBCCEmail, "Input your BCC email(s).")

            tool.SetToolTip(CheckBox1, "Enable/Disable CC emails?")
            tool.SetToolTip(CheckBox2, "Enable/Disable BCC emails?")

            tool.SetToolTip(TxtEmailSubject, "Input your email subject..")
            tool.SetToolTip(EmailMessage, "Input your email message.")
            tool.SetToolTip(ListBoxAttachmentsFiles, "List of file(s) to attach.")
            tool.SetToolTip(ButtonAttach, "Attach file(s).")
            tool.SetToolTip(ButtonRemoveFiles, "Remove file(s).")

            tool.SetToolTip(CheckBox3, "Send in Hmtl format?")
            tool.SetToolTip(RadioButton1, "Send with Low Priority?")
            tool.SetToolTip(RadioButton2, "Send with Normal Priority?")
            tool.SetToolTip(RadioButton3, "Send with High Priority?")
            tool.SetToolTip(RadioButton4, "Activate bomber?")
            tool.SetToolTip(RadioButton5, "Ativate mail count?")
            tool.SetToolTip(NumericUpDown1, "Input number of mails to send.")
            tool.SetToolTip(ButtonClearData, "Clear all information.")
            tool.SetToolTip(ButtonSend, "Send mail.")
            tool.SetToolTip(Buttonclose, "Close program.")

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub ToolStripSplitButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripSplitButton1.Click
        aboutbox()
        Me.Show()
    End Sub

    Sub aboutbox()
        Me.Hide()
        MessageBox.Show("Coder: euverve/thatskie84" + vbNewLine _
                        + "Website: http://www.ph-geeks.co.cc" _
                        + vbNewLine + vbNewLine _
                        + "Greetz to all PSVX members," _
                        + vbNewLine + "pinoygeeks, friends..." _
                        + vbNewLine + "I know who you are!" + vbNewLine _
                        + vbNewLine + "No lefts reserved." _
                        + vbNewLine + vbNewLine _
                        + "USE AT YOUR OWN RISK!", "About | Team Pinoy Geeks", _
                        MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Sub erroremail()
        Try
            Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")

            If Expression.IsMatch(TxtSenderUsername.Text) = False Or _
                TxtSenderUsername.Text.Contains("@gmail.com") = False Then
                ErrorProvider1.SetError(TxtSenderUsername, " Verify your email(s).")
            End If
            If TxtSenderPassword.Text.Length <= 7 Then
                ErrorProvider1.SetError(TxtSenderPassword, " Verify your password.")
            End If
            If Expression.IsMatch(TxtRecipientEmail.Text) = False Then
                ErrorProvider1.SetError(TxtRecipientEmail, " Verify target email(s).")
            End If

            MessageBox.Show("The email address(es) may NOT be valid." + vbNewLine _
                            + "Please verify all needed information " + vbNewLine _
                            + "before proceeding this task.")

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Email Error", MessageBoxButtons.OK, _
               MessageBoxIcon.Stop)
        End Try
    End Sub
End Class

Or view it here:
Code:
http://pastebin.com/embed_iframe.php?i=QV0VJvUF

Hope this helps others in creating their own email sender.


RE: [Source] My Gmail Email Sender - begginer - 05-12-2011

Thanks for this Source ..