contents of a text file to email body vb.net - vb.net

I want to copy all contents of a text file and paste it on the email body. I've used the code below but the body doesn't contain anything. Can somebody help me with this?
Dim lines As List(Of String) = File.ReadAllLines("C:\sendD.txt").ToList
Dim sender As String = "sender#yahoo.com"
Dim recipient As String = "receiver#yahoo.com"
Dim emailSubject = "Test!"
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
oMail.From = sender
oMail.To = recipient
oMail.Subject = emailSubject
For Each line In lines
oMail.TextBody = line
Next

Using inputReader As New IO.StreamReader("C:\sendD.txt")
oMail.Body = inputReader.ReadToEnd
End Using
or
For Each line In lines
oMail.Body = oMail.Body & VbCrLf & line
Next
or use StringBuilder, but this all questions the need for iList. not necessary with a StreamReader.
or, using your example (remove the For Each loop):
Dim lines As String = File.ReadAllText("C:\sendD.txt")
oMail.Body = lines
also, you should be using System.Net.Mail, not .Web.Mail
see: http://msdn.microsoft.com/en-us/library/system.web.mail.smtpmail%28v=vs.110%29.aspx
and: http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient%28v=vs.110%29.aspx
also, i can't find this '.TextBody' property, i think you mean .Body

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.

VB.Net - Retrieve Image from Database Column and then attach as an attachment to an email

I have an application that i am supporting. I am wondering if it is possible to retrieve an image from a database (Image Datatype) and then attach this image to an email. The application currently embeds the images to an email but i need it to attach images instead.
I have read in to adding attachments to emails but it is grabbing the image froma file location, rather than a database field. I haven't not come across anything that matches my needs.
Do i need to somehow save the image locally then send the email using the saved image?
SQL Server 2014
Pre Existing Get Image Function
Private Function GetImage() As Byte()
Dim rdrImage As SqlDataReader
Dim strSQL As String
Dim arrContent As Byte()
strSQL = "SELECT Photo FROM " & CommonThings1.GetDatabaseSuffix & "Images "
strSQL = strSQL & "WHERE PhotoID = " & Request("ZQ") & " AND Random = " & Request("WXP")
cmCM.CommandText = strSQL
rdrImage = cmCM.ExecuteReader
rdrImage.Read()
arrContent = CType(rdrImage("Photo"), Byte())
rdrImage.Close()
Return arrContent
End Function
Help is greatly appreciated.
Should go something like this, writing this off the top of my head so not tested ...
Dim stream as new MemoryStream(GetImage())
stream.Position = 0 'If I remember correctly, need to be at beginning of stream to read from first position when attaching
Dim MSG As New MailMessage
Dim ToAddress = New MailAddress(SomeEmailAddress)
Dim FromAddress As New MailAddress("SomeEmail#AnEmail.com")
Try
With MSG
.To.Add(ToAddress)
.From = FromAddress
.Subject = "Your Photo"
.IsBodyHtml = True
.Body = SomeHTML
.Attachments.Add(New Attachment(stream , "Photo.jpg", "application/jpg"))
End With
Dim SendMessage As New SmtpClient("smtp.MyMailServer.com")
SendMessage.Send(MSG)

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

How to add a string to multiple string for printing external

This is going to be a long one, but easy fix.
So i've manage to convert a pdf to string, then able to print an external pdf simply by putting the name of the file in a textbox.
I've also figured how to extract certain text from the pdf string, now the certain text are also files located in an external location (I use c:\temp\ for testing).
Which leaves me with one problem, the text I extract, I use shellexecute to print, works fine if its one string. however, If the file name I extract is more than one it will count it as a single string, thus adding the location and .pdf to that one string. instead of the two or more strings. which will do something like this:
As you can see, it will send that to the printer. I want to send one at a time to the printer. like this:
I've tried using an Arraylist and various methods. but my own lack of knowledge, I cannot figure it out.
I'm thinking a "for loop" will help me out. any ideas?
Below is my code.
Dim pdffilename As String = Nothing
pdffilename = RawTextbox.Text
Dim filepath = "c:\temp\" & RawTextbox.Text & ".pdf"
Dim thetext As String
thetext = GetTextFromPDF(filepath) ' converts pdf to text from a function I didnt show.
Dim re As New Regex("[\t ](?<w>((asm)|(asy)|(717)|(ssm)|(715)|(818))[a-z0-9]*)[\t ]", RegexOptions.ExplicitCapture Or RegexOptions.IgnoreCase Or RegexOptions.Compiled) ' This filters out and extract certain keywords from the PDF
Dim Lines() As String = {thetext}
Dim words As New List(Of String)
For Each s As String In Lines
Dim mc As MatchCollection = re.Matches(s)
For Each m As Match In mc
words.Add(m.Groups("w").Value)
Next
RawRich4.Text = String.Join(Environment.NewLine, words.ToArray)
Next
'This is where I need help with the code. how to have "words" putout "c:\temp\" & RawRich4.Text & ".pdf" with each keyword name
Dim rawtoprint As String = String.Join(Environment.NewLine, words.ToArray)
Dim defname As String = Nothing
defname = RawRich4.Text
rawtoprint = "c:\temp\" & RawRich4.Text & ".pdf"
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = (rawtoprint) ' this is where the error occurs it doesn't send both files separately to the printer, it tries to send it as one name
MessageBox.Show(rawtoprint) ' This is just to test the output, this will be removed.
'Process.Start(psi)
End Sub
Updated.
Imports System.Text.RegularExpressions
Module Program
Sub Main()
Dim pdffilename As String = RawTextbox.Text
Dim filepath = "c:\temp\" & RawTextbox.Text & ".pdf"
Dim thetext As String
thetext = GetTextFromPDF(filepath) ' converts pdf to text from a function I didnt show.
'thetext = "Random text here and everywhere ASM00200207 1 1 same here bah boom 12303 doh hel232 ASM00200208 1 2 "
Dim pattern As String = "(?i)[\t ](?<w>((asm)|(asy)|(717)|(ssm)|(715)|(818))[a-z0-9]*)[\t ]"
For Each m As Match In rgx.Matches(thetext, pattern)
'Console.WriteLine("C:\temp\" & Trim(m.ToString) & ".pdf")
RawPrintFunction("C:\temp\" & Trim(m.ToString) & ".pdf")
Next
End Sub
Function RawPrintFunction(ByVal rawtoprint As String) As Integer
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
MessageBox.Show(rawtoprint) This will be removed, this is just for testing to see what files will be printed
'Process.Start(psi) This will be uncomment.
return 0
End Function
End Module
If I don't misunderstand the code -since I can't test and run it here- you can iterate through file names stored in words variable and send it to printer. Following is an example on how to do that :
....
....
Dim Lines() As String = {thetext}
Dim words As New List(Of String)
For Each s As String In Lines
Dim mc As MatchCollection = re.Matches(s)
For Each m As Match In mc
words.Add(m.Groups("w").Value)
Next
RawRich4.Text = String.Join(Environment.NewLine, words.ToArray)
Next
For Each fileName As String In words
Dim rawtoprint As String
rawtoprint = "c:\temp\" & fileName & ".pdf"
Dim psi As New System.Diagnostics.ProcessStartInfo()
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = (rawtoprint) ' this is where the error occurs it doesn't send both files separately to the printer, it tries to send it as one name
MessageBox.Show(rawtoprint) ' This is just to test the output, this will be removed.
'Process.Start(psi)
Next

VB.NET OpenXML to Read Excel File

I have been searching for a way to effectively read an Excel file and have found the following code for parsing and reading a large spreadsheet:
Public Sub ExcelProcessing()
Dim strDoc As String = "C:\Documents and Settings\Practice.xlsx"
Dim txt As String
Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open(strDoc, False)
Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart
Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First()
Dim reader As OpenXmlReader = OpenXmlReader.Create(worksheetPart)
Dim text As String
While reader.Read()
If reader.ElementType = GetType(CellValue) Then
text = reader.GetText()
MessageBox.Show(text)
End If
End While
The issue is where I assign reader.GetText() to my string. The value passed is a small integer while the actual cell value is a string. The messagebox fires once for each populated cell, so this tells me the code is finding cells that contain values; however, I can not extract the actual "inner text" of the cell.
Thoughts? Suggestions?
I found my answer; I need to reference the sharedstringtable and pull out the inner text from there:
Dim strDoc As String = "C:\Documents and Settings\Practice.xlsx"
Dim txt As String
Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open(strDoc, False)
Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart
Dim shareStringPart As SharedStringTablePart = workbookPart.SharedStringTablePart
For Each Item As SharedStringItem In shareStringPart.SharedStringTable.Elements(Of SharedStringItem)()
MessageBox.Show(Item.InnerText)
Next