How to search for files and attach them to a Email - vb.net

I have an CheckedListbox (imported from mysql Database) that lists all my folders where my files are saved. And what I need to do is for every checked item in the CheckListbox, to search the folder and then attach the file from that folder to a Mail.
What I have done is to create an Email and to send it with only one attachment.
Just with the: "e_mail. Attachments. Add". The Mail will be generated and that found file will be attached and send.
But when I do that in a FOR EACH LOOP then no file will be selected and added to my Mail. The Mail will be generated and send without any errors, but there are no attached files.
Private Sub SendMail()
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("MAIL", "PASS")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp_Server.Host = "HOST"
If MonthTextBox.Text = "" Or MonthTextBox.ForeColor = Color.Silver Then
MsgBox("Input month please", Title:="MO Text Box")
Else
Dim MOTextValue As String = MonthTextBox.Text
Dim nowYear As Integer = Date.Now.Year
For Each itemchecked As DataRowView In CheckedListBoxWO.CheckedItems
Dim File_path As String = "C:\Test\" & itemchecked.Item(1) & "\" & nowYear & "\" & MOTextValue & "\"
Dim File_Name As String = Dir("C:\Test\" & itemchecked.Item(1) & "\" & nowYear & "\" & MOTextValue & "\File " & MOTextValue & "*.xlsx")
Dim attachmentFile As Net.Mail.Attachment = New Net.Mail.Attachment(File_path & File_Name)
e_mail.Attachments.Add(attachmentFile)
Next
Dim sb As New System.Text.StringBuilder
sb.AppendLine("Hello,<br />")
sb.AppendLine("<br />")
sb.AppendLine("Test Attachment,<br />")
sb.AppendLine("<br />")
sb.AppendLine("------------------------------------------<br />")
e_mail.From = New MailAddress("MY MAIL")
e_mail.To.Add("EMAIL")
e_mail.Subject = ("TESTFILE - " & MOTextValue & "")
e_mail.SubjectEncoding = System.Text.Encoding.UTF8
e_mail.IsBodyHtml = True
e_mail.Priority = MailPriority.Normal
e_mail.Body = sb.ToString()
e_mail.BodyEncoding = System.Text.Encoding.UTF8
Smtp_Server.Send(e_mail)
End If
MsgBox("Mails was sent", Title:="Mail")
End Sub
Like I told with this code the Mail will be created and send, but there is no Attachment file in it.
If I do it without the "FOR EACH"... loop, then one File will be added without a problem. But I need to add more files, actually for every checked Item in the CheckedListBox my program should search that folder and if there is a file than attach it in the Mail, and look in the other folder and so on...

Your adding attachments then newing up your e_mail object again, this will wipe your existing data, try removing the indicated line below:
sb.AppendLine("<br />")
sb.AppendLine("------------------------------------------<br />")
e_mail = New MailMessage() <--- remove this line
e_mail.From = New MailAddress("MY MAIL")
e_mail.To.Add("EMAIL")

The code is actually working, my problem was that the reference to this CheckListBox was incorrect, I have multiple CheckListBoxes, and that one in the Code was not the one I was actually using... But looking it from the bright side, THE CODE IS WORKING :)

Related

Cant attached printed pdf document as email attachment in VB.net

I am able to create a pdf document and I can browse the folder and open the document with no issue. But when my code try to attach the file as an attachment then it fails with this error, but the path and filename is correct. I suspect the file is somehow open which prevents the attachment.
Proof of files:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
Could not find file 'C:\TEMP\1104280343081_INV0950.pdf'.
This part works perfectly
Dim txtVarFile As String
Dim txtVarEmail As String = "test#test.com"
Dim txtVarPasss As String = "password"
Dim txtVarSMTP As String = "smtp.gmail.com"
Dim intVarPort As Integer = 587
Dim txtVarDescription As String
'Create Invoice and Save as pdf document
txtVarFile = "C:\TEMP\" & strClientNum & "_" & strInvNum & ".pdf"
PageSetupDialog1.Document = PrintDocument1
PageSetupDialog1.PrinterSettings.DefaultPageSettings.Landscape = True
prtFrmInvoice.PrinterSettings = PageSetupDialog1.PrinterSettings
If prtFrmInvoice.PrinterSettings.IsValid Then
prtFrmInvoice.PrinterSettings.PrinterName = "Microsoft Print to PDF"
prtFrmInvoice.PrintFileName = txtVarFile
prtFrmInvoice.PrintAction = Printing.PrintAction.PrintToFile
prtFrmInvoice.Print()
End If
But this does not work, it tells me the file can not be found, but the file is there
Exception is thrown at this line: eMail.From = New MailAddress(txtVarEmail)
'Send copy of Invoice per Email
Try
Dim SmtpServer As New SmtpClient()
Dim eMail As New MailMessage()
'Dim attachment As System.Net.Mail.Attachment
LogFile.Refresh()
SmtpServer.UseDefaultCredentials = False
SmtpServer.Credentials = New Net.NetworkCredential(txtVarEmail, txtVarPasss)
SmtpServer.Port = intVarPort
SmtpServer.EnableSsl = True
SmtpServer.Host = txtVarSMTP
eMail = New MailMessage()
eMail.From = New MailAddress(txtVarEmail)
eMail.To.Add(strClientEmail)
eMail.Subject = "AltHealth Invoice"
eMail.Body = "Please find your latest invoice attached"
'attachment = New System.Net.Mail.Attachment(txtVarFile)
'eMail.Attachments.Add(attachment)
eMail.Attachments.Add(New Attachment(txtVarFile))
SmtpServer.Send(eMail)
MsgBox("The Invoice has been sent sucessfully via email - File: " & txtVarFile)
Catch ex As Exception
MsgBox("Send failure: " & ex.ToString())
End Try

UWP epPlus - choose directory to save

I am making an application in vb using UWP and epPlus along with it to save the current database to an excel file. I would create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. There isn't a "Savefiledialog" in UWP... Ideas?
UPDATE
I tried to use FileSavePicker: if I save it in the principal directory (C:\, Desktop, Documents ...) epPlus doesn't work, but if I save it in another directory (D:\, USB...) it workes... How can I save it in the principal directory?
I post my code here:
Private Async Sub ButtonXls_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
OutputTextBlock.Text = ""
Dim savePicker As FileSavePicker = New FileSavePicker()
savePicker.SuggestedStartLocation = PickerLocationId.Desktop
savePicker.FileTypeChoices.Add("Microsoft Excel", New List(Of String)() From {
".xlsx"
})
savePicker.SuggestedFileName = "Riepilogo_Test"
Dim file As StorageFile = Await savePicker.PickSaveFileAsync()
If file IsNot Nothing Then
CachedFileManager.DeferUpdates(file)
Dim ExcelPkg As ExcelPackage = New ExcelPackage()
Dim wsSheet1 As ExcelWorksheet = ExcelPkg.Workbook.Worksheets.Add("Sheet1")
Using Rng As ExcelRange = wsSheet1.Cells(2, 2, 2, 2)
Rng.Value = "Text file on Excel here"
Rng.Style.Font.Size = 16
Rng.Style.Font.Bold = True
Rng.Style.Font.Italic = True
End Using
wsSheet1.Protection.IsProtected = False
wsSheet1.Protection.AllowSelectLockedCells = False
Dim filePath As FileInfo = New FileInfo(file.Path)
ExcelPkg.SaveAs(filePath)
Dim status As FileUpdateStatus = Await CachedFileManager.CompleteUpdatesAsync(file)
If status = FileUpdateStatus.Complete Then
OutputTextBlock.Text = "File " & file.Name & " was saved."
ElseIf status = FileUpdateStatus.CompleteAndRenamed Then
OutputTextBlock.Text = "File " & file.Name & " was renamed and saved."
Else
OutputTextBlock.Text = "File " & file.Name & " couldn't be saved."
End If
Else
OutputTextBlock.Text = "Operation cancelled."
End If
End Sub

How to get file's path created by this code?

I'm using this code to save files in my app
Dim filePath = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
PictureBox1.Image.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filePath)))
So now I have a textbox1 and I want to show the path of last saved image in it
how?
Regards,,,,
What I've done in the past is generate the path in one step and then use the generated variable to do the saving and to display.
So instead of:
Dim filePath = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
PictureBox1.Image.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filePath)))
Try:
'Generate the Path
Dim path As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now))
'Save using the generated path
PictureBox1.Image.Save(path)
'Display the path
textbox1.Text = path
Thanks all I've done it successfully `
Dim filename As String = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
Dim filePath1 = (IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filename)))
Dim filePath2 = (IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ("RMSS")))
If IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (" RMSS"))) = True Then
TextBox1.Text = filePath1
TextBox2.Text = filePath2 & "\" & filename
PictureBox1.Image.Save(filePath1)
My.Computer.FileSystem.MoveFile(TextBox1.Text, TextBox2.Text, True)
Else
TextBox1.Text = filePath1
TextBox2.Text = filePath2 & "\" & filename
PictureBox1.Image.Save(filePath1)
My.Computer.FileSystem.MoveFile(TextBox1.Text, TextBox2.Text, True)
End If

error deleting files after I send an email using VB Studio

Below is the email code I am using to send an email with attached document, but when I try to delete the files it is showing that the files are in use. Any help will be appreciated.
Sub email()
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim body As String
Dim address As String
Dim address2 As String
Dim address3 As String
Dim fileReader As System.IO.StreamReader
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\VB Test\location.txt")
Dim Pathstore As String
Pathstore = fileReader.ReadLine()
'email address
Dim lines() As String = System.IO.File.ReadAllLines("C:\VB Test\stores.txt")
For Each line As String In Filter(lines, Pathstore)
Dim fields() As String = line.Split(",")
address = fields(4)
address2 = fields(2)
address3 = fields(6)
Next
Dim fileReader2 As System.IO.StreamReader
fileReader2 = My.Computer.FileSystem.OpenTextFileReader("C:\VB Test\rmmsiul.dll")
Dim Pathcode As String
Pathcode = fileReader2.ReadLine()
fileReader2.Close()
body = "Here are the manual reciepts I created today." + vbNewLine + vbNewLine + vbNewLine & "Thank you," + vbNewLine + Pathstore
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("Do-Not-Reply#suncommobile.com", Pathcode)
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.office365.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("Do-Not-Reply#suncommobile.com")
e_mail.CC.Add(address)
e_mail.CC.Add(address2)
e_mail.CC.Add(address3)
e_mail.Subject = Pathstore + " Manual reciepts"
e_mail.IsBodyHtml = False
e_mail.Body = body
Dim filepath As String
For Each filepath In Directory.GetFiles("C:\VB Test\Receipts")
Dim Attach As New Net.Mail.Attachment(filepath)
e_mail.Attachments.Add(Attach)
Kill(filepath)
Next
Smtp_Server.Send(e_mail)
MsgBox("E-mail Sent.")
Module1.filedelete()
End Sub
'changed part of the code to the following, but getting error when sending email.
For Each filepath As String In Directory.GetFiles("C:\VB Test\Receipts")
Using reader As New StreamReader(filepath)
Dim a As New Net.Mail.Attachment(reader.BaseStream, filepath)
e_mail.Attachments.Add(a)
End Using
Next
Smtp_Server.Send(e_mail)
Public Sub email()
Dim Pathstore As String = String.Empty
Dim Pathcode As String = String.Empty
With New StreamReader("C:\VB Test\location.txt")
Pathstore = .ReadLine()
.Dispose()
End With
' Are you sure this is the correct file ?
With New StreamReader("C:\VB Test\rmmsiul.dll")
Pathcode = .ReadLine()
.Dispose()
End With
' Capture the list of Attachment Files here, then use it twice below
Dim Attachments() As String = Directory.GetFiles("C:\VB Test\Receipts")
Dim e_mail As New Net.Mail.MailMessage()
With e_mail
.From = New Net.Mail.MailAddress("Do-Not-Reply#suncommobile.com")
.Subject = String.Format("{0} Manual reciepts", Pathstore)
.Body = String.Format("Here are the manual reciepts I created today.{0}{0}{0}Thank you,{0}{1}", Environment.NewLine, Pathstore)
' Since I don't know what Filter() returns, this is best guess to reproduce the same outcome
For Each line As String In Filter(File.ReadAllLines("C:\VB Test\stores.txt"), Pathstore)
Dim fields() As String = line.Split(",")
.CC.Clear()
.CC.Add(fields(4))
.CC.Add(fields(2))
.CC.Add(fields(6))
Next
For Each filepath In Attachments
.Attachments.Add(New Net.Mail.Attachment(filepath))
Next
End With
With New Net.Mail.SmtpClient
.Host = "smtp.office365.com"
.Credentials = New Net.NetworkCredential("Do-Not-Reply#suncommobile.com", Pathcode)
.Port = 587
.EnableSsl = True
.Send(e_mail)
End With
' Dispose the MailMessage to release the holds on the Attachment Files
e_mail.Dispose()
' Delete the Attachment Files
For Each filepath In Attachments
File.Delete(filepath)
Next
MsgBox("E-mail Sent.")
End Sub

Saving data with a file name of my choice

Very kindly, an intelligent member of stack overflow showed me how to loop with 'Do Until' and generate messages boxes to enable a user to save a file or rename one, if it already exists. However, I'm still hitting a wall. I can't save the ListView data in my for loop, with the file name I have chosen in the Input Box (see code below). Its like I have two separate pieces of code because rtb is saving data in a Rich Text File called Test.txt and saveFile has nothing to do with this! Please help
Code
Dim fileSaved As Boolean
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'THIS NEXT bit of code saves content to Test.txt NOT saveFile as desired!
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile("C:\Users\SMITH\Documents\Visual Studio 2013\Projects\Test.txt", _
RichTextBoxStreamType.PlainText)
When you try to save the file with the RichTextBox method SaveFile you need to be able to use the variable filePath that receive the input from your user. But this variable is declared inside the block Do Until .... Loop and according to scope rules of variables in VB.NET is not available outside that block. You could move the declaration of the variable before entering the loop
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs as String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
' The remainder of your code can be left unchanged until the SaveFile line
Now you could use it in the call
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)