Find & Replace text in a email (oft or msg) - vb.net

Thankyou for stopping by to look at my question.
I’m trying to replace text in an email (oft or msg).
I’m trying to find.
##TEST1## and replace with textbox1.text
##TEST2## and replace with textbox2.text
##TEST3## and replace with textbox3.text
I have found the following to open the email template and this works a treat.
Dim Outl As Object
Outl = CreateObject("Outlook.Application")
If Outl IsNot Nothing Then
Dim omsg As Object
omsg = Outl.CreateItemFromTemplate("C:\Testing\EmailSerials.oft")
omsg.To = "yusuf#hotmail.com"
omsg.subject = "Hello, Please find your Software"
omsg.Display(True)
End If
i'm new at this so any help or examples would be great.
Manty thanks
James

Take a look at [MailItem].Body and String.Replace
I worked on the assumption that the OFT file had content you wish to replace. I also took the opportunity to replace the VB6 code with VB.Net version.
Add a reference to:
Microsoft.Office.Interop.Outlook
And, also add this to the top of the file:
Imports Microsoft.Office.Interop
And then the code to replace the text you are wanting to replace
Dim Outl As New Outlook.Application
If Outl IsNot Nothing Then
Dim omsg As Outlook.MailItem = CType(Outl.CreateItemFromTemplate("C:\Testing\EmailSerials.oft"), Outlook.MailItem)
omsg.To = "yusuf#hotmail.com"
omsg.subject = "Hello, Please find your Software"
omsg.Body = omsg.Body.Replace("##TEST1##", textbox1.text)
omsg.Body = omsg.Body.Replace("##TEST2##", textbox2.text)
omsg.Body = omsg.Body.Replace("##TEST3##", textbox3.text)
omsg.Display(True)
End If

Related

VB App is freezing when displaying Outlook Object

I have code that upon click, opens up a pre-defined Outlook Message.
My problem is, when the Outlook message window opens, my VB.Net app freezes until, the Outlook message window is either closed or the mail is sent.
How can I release the object from vb.net so the my app is normal to use and not frozen in time?
My Code:
Dim EmailImgPath, strMsg As String
If CustID = vbEmpty Then
MsgBox("No Client selected. Please select a client first before clicking on the Notifications Email button.", vbExclamation + vbOKOnly, "No Client Selected")
Else
If cmbOrdStatus.Text = "Ready" Then
Try
Dim Outl As Object
Outl = CreateObject("Outlook.Application")
If Outl IsNot Nothing Then
Dim omsg As Object
omsg = Outl.CreateItem(0) '=Outlook.OlItemType.olMailItem'
omsg.To = txtEmail1.Text
omsg.cc = txtEmail2.Text
omsg.bcc = EmailBcc
omsg.subject = "Order Update from EyeStyle Opticians"
strMsg = strMsg & "<p>Dear " & txtFname.Text & ",<br><br>"
strMsg = strMsg & "<p>Great News!"
strMsg = strMsg & "<p>Your order is ready for collection"
strMsg = strMsg & "<p>For any enquiries please call 0734 544376 / 0726 936136 / 0707 908838"
strMsg = strMsg & "<p>Thank you for your patronage and assuring you of our very best services at all times."
strMsg = strMsg & "<p>Karibu."
strMsg = strMsg & "<p>Eyestyle Opticians Ltd.<br><br>"
strMsg = strMsg & "<p><img src=" & EmailImgPath & "></p>"
omsg.HTMLBody = strMsg
omsg.Display(True) 'will display message to user
End If
Outl = Nothing
Catch ex As Exception
MessageBox.Show("ERROR: Failed to send mail: " & ex.Message)
End Try
End If
The following shows how to use Microsoft.Office.Interop.Outlook to send an e-mail. It's been tested.
Pre-requisite: Outlook installed.
Add Reference:
Note: The instructions below are for VS 2019.
In VS menu, click Project
Select Add Reference...
Click COM
Check Microsoft Outlook xx.x Object Library (ex: Microsoft Outlook 16.0 Object Library)
Click OK
Add Imports statement
Imports Outlook = Microsoft.Office.Interop.Outlook
CreateMsg:
Private Sub CreateMsg(toAddress As String)
Dim oApp As Outlook.Application = Nothing
Dim oNS As Outlook.NameSpace = Nothing
Try
'create new instance
oApp = New Outlook.Application()
'get MAPI namepsace
oNS = oApp.GetNamespace("mapi")
'log on using default profile
oNS.Logon()
'logon using specified profile
'oNS.Logon("profileName", System.Reflection.Missing.Value, False, true)
'create MailItem
Dim oMsg As Outlook.MailItem = DirectCast(oApp.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
'ToDo: change the message properties as desired (ie: subject, body, etc...)
oMsg.To = toAddress
oMsg.Subject = "this is the subject"
oMsg.Body = "This is a test " & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")
'send message
For Each account As Outlook.Account In oApp.Session.Accounts
Debug.WriteLine($"account SMTP address: {account.SmtpAddress}")
If account.SmtpAddress = "desiredFromAddress#outlook.com" OrElse oApp.Session.Accounts.Count = 1 Then
Debug.WriteLine($"Sending from {account.SmtpAddress}...")
oMsg.SendUsingAccount = account
oMsg.Send()
Exit For
End If
Next
'sleep to allow send to complete
System.Threading.Thread.Sleep(150)
'send and receive
oNS.SendAndReceive(False)
'log off
oNS.Logoff()
'oMsg.Display(True)
'oMsg.Display(False)
Finally
If oApp IsNot Nothing Then
oApp.Quit()
End If
End Try
End Sub
Resources:
Microsoft.Office.Interop.Outlook
Work with mail items
How to: Programmatically create an email item
Outlook Automatic Send Receive not Working (Solved)
COM Interop & Outlook - Make Outlook Visible?
How to use the Microsoft Outlook Object Library to retrieve a message from the Inbox by using Visual C#
How to send a mail using Microsoft.Office.Interop.Outlook.MailItem by specifying the From Address
How To: Perform Send/Receive in Outlook programmatically
Outlook error when sending more than one mail: "The item has been moved or deleted"
Outlook Interop: MailItem stuck in Outbox
Outlook Integration in C#

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.

Visual Basic, Capture output from cmd

Sorry if it's asked before, I found out other Solutions too complicated for me..
Anyway, i am trying to search an image via cmd in visual basic code, and save the image path to string, but i cant seem to capture the output from cmd right.
Any help will be appreciated, thanks!.
Code:
Dim imageLocation As String
Dim cmd As New Process
Dim SR As System.IO.StreamReader
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.StartInfo.Arguments = "/C dir /b/s Roey.png"
cmd.Start()
SR = cmd.StandardOutput
imageLocation = SR.ReadLine
UPDATED So i found out saving the output to txt file and then read it can be more simple, so i wrote the following code:
Dim cmd As New Process
cmd.StartInfo.FileName = "cmd.exe"
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
cmd.StartInfo.Arguments = "/C dir /b/s Roey.png >
C:\Users\ירין\Desktop\Roeyyy\path.txt"
cmd.Start()
cmd.WaitForExit()
when i run the
"dir /b/s Roey.png >
C:\Users\ירין\Desktop\Roeyyy\path.txt"
on CMD it wors perfectly, so why isnt it working here? :(
I found this:
Dim MyFilePath As String = Directory.GetFiles([SomePath], "*.png", SearchOption.AllDirectories).
Where(Function(f) f.Contains("Roey.png")).FirstOrDefault()
Solved!
You are a programmer so you search for files.
Imports System.Runtime.InteropServices
Sub Main
'On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
End Sub
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.path
'fso.copyfile thing.path, "C:\backup"
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub

NullReferenceException was unhandled by user code - declaring Excel.Worksheet object

I'm transitioning from Excel VBA to VB.NET, so if this is a dumb question, please go easy on me. I get a NullReferenceException was unhandled by user code on this line of the following sub:
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
VS says that the Object reference is not set to an instance of the object. I'm not sure why it's asking for that, because I've already declared a new instance of Excel in the objApp variable. Why would I need to declare a new instance of each object under that class? It's very possible I'm not thinking about that correctly, but I just wanted to mention my thoughts. Overall, I'm just trying to test the sub below to see if it will open and close a connection to a PostgreSQL database.
Imports Microsoft.Office.Interop
Public Sub QueryData(ByVal ribbonUI As Office.IRibbonControl)
Dim objApp As New Excel.Application
Dim objBook As Excel.Workbook = objApp.ActiveWorkbook
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
Dim pgconn As String
pgconn = "Driver={PostgreSQL};" &
"Server = localhost;" &
"Port = 5432;" &
"Database = CFABudget;" &
"Uid = postgres;" &
"Pwd = budgeto;"
Dim SQL As String = objSheet.Range("BudgetSQL").Text
Dim conn As New Data.Odbc.OdbcConnection(pgconn)
Dim cmd As Data.Odbc.OdbcCommand = New Data.Odbc.OdbcCommand(SQL)
conn.Open()
MsgBox("Success!", vbOKOnly)
conn.Close()
End Sub
Thank you all for your help!
Replace
Dim objApp As New Excel.Application
With:
Dim objApp As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
You were trying to get active workbook from new empty instance of excel.

contents of a text file to email body 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