Cant attached printed pdf document as email attachment in VB.net - 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

Related

VB.net Crystal report export to html and send as html mail body using outlook

I am trying to send contents of a crystal report as email body using outlook application.
Here is my code in VB.net
Imports outlook = Microsoft.Office.Interop.Outlook
Dim a As String = something.ConnectionString
Dim cryRpt As ReportDocument
Dim username As String = a.Split("=")(3).Split(";")(0) 'get username
Dim password As String = a.Split("=")(4).Split(";")(0) 'get password
cryRpt = New ReportDocument()
Dim Path As String = Application.StartupPath
Dim svPath As String = Application.StartupPath & "\PDF"
If Not Directory.Exists(svPath) Then
Directory.CreateDirectory(svPath)
End If
cryRpt.Load(Path & "\Reports\dr.rpt")
CrystalReportViewer1.ReportSource = cryRpt
cryRpt.SetDatabaseLogon(username, password)
CrystalReportViewer1.Refresh()
Dim myExportOptions As ExportOptions
myExportOptions = cryRpt.ExportOptions
myExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
myExportOptions.ExportFormatType = ExportFormatType.HTML40 'i tried HTML32 also
Dim html40FormatOptions As HTMLFormatOptions = New HTMLFormatOptions()
html40FormatOptions.HTMLBaseFolderName = svPath
html40FormatOptions.HTMLFileName = "dr.htm"
html40FormatOptions.HTMLEnableSeparatedPages = False
html40FormatOptions.HTMLHasPageNavigator = False
html40FormatOptions.UsePageRange = False
myExportOptions.FormatOptions = html40FormatOptions
cryRpt.Export()
Try
Dim oApp As outlook.Application
oApp = New outlook.Application
Dim oMsg As outlook.MailItem
oMsg = oApp.CreateItem(outlook.OlItemType.olMailItem)
oMsg.Subject = txtSubject.Text
oMsg.BodyFormat = outlook.OlBodyFormat.olFormatHTML
oMsg.HTMLBody = ""
oMsg.HTMLBody = getFileAsString(svPath & "\PoPrt\QuotPrt.html")
oMsg.To = txtEmailId.Text
Dim ccArray As New List(Of String)({txtCC1.Text, txtCC2.Text, txtCC3.Text})
Dim cclis As String = String.Join(",", ccArray.Where(Function(ss) Not String.IsNullOrEmpty(ss)))
oMsg.CC = cclis
oMsg.Display(True)
Catch ex As Exception
MsgBox("Something went wrong", vbExclamation)
End Try
SvFormPanel3.Visible = False
the function
Private Function getFileAsString(ByVal file As String) As String
Dim reader As System.IO.FileStream
Try
reader = New System.IO.FileStream(file, IO.FileMode.Open)
Catch e As Exception
MsgBox("Something went wrong. " + e.Message, vbInformation)
End Try
Dim resultString As String = ""
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While reader.Read(b, 0, b.Length) > 0
resultString = resultString & temp.GetString(b)
Array.Clear(b, 0, b.Length)
Loop
reader.Close()
Return resultString
End Function
The report will get exported to the specified location as html. And when we manually open that html file it displays perfectly with border lines and all.
But when its getting added as html body of outlook application, the formatting will be gone, and looks scattered.
can anyone help
Did you try this?
Open outlook, go to, File>Options>Mail
go to section MessageFormat and untick "Reduce message size by removing format..."
I have solved the issue by exporting it into PDF and then convert to Image and embed in email body.

How to search for files and attach them to a Email

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

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

Attach all files in a folder to an email

I am trying to make a ConsoleApplication attach all files in a folder to an email and send it. I know how to do it with a single attachment, but for the life of me, I cannot figure out how to attach all items in a folder.
Current code:
Sub Main()
Try
Dim mail As New MailMessage("from", "to")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
Dim file As System.Net.Mail.Attachment
file = New System.Net.Mail.Attachment("Path to single file")
mail.Attachments.Add(file)
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub
Thanks in advance
EDIT:
I tried the below code that I found on another post, but it just errors out (and using the ConsoleApplication, I am not sure how to view the exact error its giving)
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
I got it working!
Sub Main()
Try
Dim mail As New MailMessage("from", "too")
Dim client As New SmtpClient()
client.Port = 25
client.DeliveryMethod = SmtpDeliveryMethod.Network
client.UseDefaultCredentials = False
client.Host = ""
mail.Subject = "" + DateTime.Now.AddDays(-1).ToShortDateString()
mail.IsBodyHtml = True
mail.Body = "Test"
For Each filePath As String In Directory.GetFiles(My.Settings.FileLoc1)
Dim Attach As New Net.Mail.Attachment(filePath)
mail.Attachments.Add(Attach)
Next
client.Send(mail)
Return
Catch [error] As Exception
MsgBox("error")
Return
End Try
End Sub

An asynchronous call is already in progress. It must be completed or canceled in vb.net

I am trying to send a mail to more than one person at a time.
My code is like this;
Dim SmtpServer As New SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("jasibs002#gmail.com", "solutions")
SmtpServer.Port = 25
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Dim omail As New MailMessage()
omail.From = New MailAddress("jasibs002#gmail.com", "JaseemBinBacker", System.Text.Encoding.UTF8)
omail.Subject = "Test Mail"
Dim str As String
str = "Hai How Are You I am Sendig This Mail for Testing"
str = str + vbNewLine & "Checking"
str = str + vbNewLine & "Sucess"
omail.Body = str
Dim email As String
Dim cmdemail As New SqlCommand("SELECT Emailid FROM dbo.Email_tbl", con.connect)
dr = cmdemail.ExecuteReader
While dr.Read
email = dr("Emailid")
omail.To.Add(email)
SmtpServer.SendAsync(omail, Nothing)
End While
dr.Close()
con.disconnect()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
While executing this, I am getting the following error;
An asynchronous call is already in progress. It must be completed or canceled before you can call this method.
My Email Table has more than 10 email ids.
I want send this email at the same, how I can do this?