Why is my StreamReader reading the title of the text file? - vb.net

So I'm working on my A Level coursework and have hit a block that I can't seem to work out. Basically, I have a bit of code that sends an email using text from a text file as well as a bit of hard coded text, all put into one variable before being passed onto the subroutine for sending an email.
I'm using a stream reading for both the email subject and body (as they're each in separate text files) and, while they're working fine elsewhere in the program, they're not working here. Rather than putting the contents of the text file into the variable before it's used to send an email, they're just putting the name of the text file there.
Also, the name of the file does not appear anywhere in the text stored within
E.g. The body of the email that it sent had the hard coded message and then it just said 'AbsenceEmailBody' (name of the text file) rather than what was inside the text file itself
Here's the lines of code where the files are read and put into variables
Dim objReaderSubject As New System.IO.StringReader("AbsenceEmailSubject")
Dim objReaderBody As New System.IO.StringReader("AbsenceEmailBody")
Dim EmailBody As String
Dim EmailSubject As String
EmailBody = "Dear " & CadetDS.Tables("CADET").Rows(0).Item("CadetFirstName") & "," & vbNewLine & vbNewLine & "It has come to the staff's attention that you have attended only " & ProblemAttendances(i, 1, 0, 0, 0) & "% of sessions." & vbNewLine & objReaderBody.ReadToEnd
EmailSubject = objReaderSubject.ReadToEnd
I also check the files exist before any of this
If System.IO.File.Exists("AbsenceEmailSubject") = True And System.IO.File.Exists("AbsenceEmailBody") = True Then
I've looked around everywhere and can't seem to find an answer. Also, this is my first time ever asking a question on here (or anywhere online) so if you need any more information just ask

Related

Email body line by line

I use email to send my emails out. In body clause i use this code below. In bodyText variable i insert text comming from stringbuilder. However at the end when my email is received all text are not line b line but in one line. What am i doing wrong?
Mail.Body = "<HTML><HEAD></head><BODY style='font-size: 11px; font-family: Tahoma'>" + "<P>" & "Hi there," & ",</p>" + "<p>" & bodyText & "</p>" & "<p>This e-mail is generated automatically therefore <b>do not reply to this email.</b></p>" + "<p>Developer, </p>" & "Development team" & "</BODY></HTML>"
Stringbuilder:
_strbuild.Append("Start" + Environment.NewLine).AppendLine()
_strbuild.Append("Start" + Environment.NewLine).AppendLine()
You create some HTML so you have to use the HTML new line (<br>):
_strbuild.Append("Start" + "<br>")
_strbuild.Append("Start" + "<br>")
Instead of using the system new line (\r\n or \n) you have to use the <br> element. In HTML you can use the system new line only to format the HTML code not to format the output.
When the body of the message is sent in HTML format, add the (break - br) tags right in your String. vbCrLf and StringBuilder are not suggested as they don't work if the body is in HTML format.
Dim mail As New MailMessage
mail.IsBodyHtml = True
mail.Body = "Line one<br>"
mail.Body += "Line Two<br>"
mail.Body += "More Lines"
Environment.NewLine does not work because the current environment for your program is not the same environment where the user will read your result. Your environment is a console program (masquerading as a scheduled task or service), or web server application, or windows form, or something else where outputting a simple \n character results in a new line. The same applies to AppendLine(). It's using Environment.NewLine behind the scenes, and again, the problem is that your program environment is different than your user's environment.
In this case, your user's environment is an html document. HTML treats all simple whitespace the same, as a single space. This is true whether you have a tab, newline, space, or any multiples or combination of the above. It all consolidates to a single space in html.
So for html, in order to force a line break, you should instead include a <br> tag with your html. More than this, HTML will break up the lines automatically; you might get away without doing anything. Even in cases where you want an explicit line break what you're typically really doing from a semantic standpoint is asking for a new paragraph. This means <p> is commonly more appropriate:
_strbuild.Append("Start").Append("<p>")
If you really don't want the extra blank line from the new paragraph you can use styles to remove or reduce it (though admittedly e-mail is the one place where breaking the correct p vs br semantics might be appropriate: e-mail renderers can be difficult).

VBA Hyperlinks.Add method prepending local folder to Address

I've been lurking here for a while but this is my first post so let me know if I need to change something. Anyways, here goes:
I'm trying to create a macro that will add hyperlinks to cells in a worksheet. The problem is that after running the macro, I notice that the folder location of my spreadsheet has been prepended to the address that I specified. Is there something I need to do in order to indicate that this is a webpage and not a local file? Excerpt from the macro is below.
Dim IGQ As Range
Dim IGQno As String
Dim IGQno1 As String
For Each IGQ In Range("A2:A10") 'Actual range is much larger
IGQno = IGQ.Value
IGQno1 = Left(IGQ, 1)
Sheets("Cameron DCDA").Hyperlinks.Add Anchor:=IGQ, _
Address:="""http://xxxx""&IGQno1&""xxx""&IGQno&""xxxxx""" 'It's a company website so they probably don't want me to share it
Next
The result is that a hyperlink is created for each cell but it links to file:///C:\Users\John.Doe\Documents\"http://xxxx"&IGQno1&"xxx"&IGQno&"xxxxx"
I've tried using fewer quotation marks in the address since it seems like overkill but I get the compile error "Expected: end of statement"
Do you guys have any suggestions?
Too many quotes
Address:="http://xxxx " & IGQno1 & "xxx" & IGQno & "xxxxx"
Also - be sure to leave a space before your & otherwise it will be interpreted as a variable type suffix:
What are possible suffixes after variable name in VBA?

Creating Multiple Links in an Access Textbox

I have a form in Access 2016 with a textbox in which I need to have multiple, semi-colon delimited hyperlinks (which will be dynamically created). What I've decided to do is create a "hyperlink construction string" in VBA, then assign them to the value of the textbox. So, something like:
Me.Field.Value = {link: www.google.com : "Google"} & "; " & {link: www.yahoo.com : "Yahoo"}
...would result in this being in the text box:
Google; Yahoo
My problem is, I can't seem to figure out the syntax to create an individual link in the textbox without making the entire textbox a single hyperlink, which isn't gonna work.
I was working with a few solutions that I've found. I read that this would create the link in the way I need, but it just comes through as literal text with the pound signs:
"Google # www.google.com # Some Argument"
I also tried setting the textbox to rich text, then setting the value to include rich text code for a hyperlink... but that's not working:
"{\field{\*\fldinst HYPERLINK ""http://www.google.com/""}{\fldrslt http://www.google.com}}"
I also thought about designing a Query that will return the hyperlinks. But, I kind of wanted to make it a VBA thing, because I'll have more flexibility in how I create the value. Does anyone have any ideas?
Note: I understand that multiple values should be in a 1:M relational database. They are. But, the requirements of the task are to get all the M values for a 1 entity, then list them out in semi-colon, delimited fashion, which all serve as links to a Details table for the M entity.
Regular textboxes (text only) don't support this.
It is possible with Rich text textboxes. In contrast to the name, they actually use a subset of HTML, not RTF.
With ideas from here I got this working:
Private Sub cmdInsertHyperlinks_Click()
Dim url1 As String, url2 As String
url1 = "D:\tmp\test.jpg"
url2 = "D:\tmp\test space.txt"
Me.rText.Value = "<div>" & _
"file://" & url1 & "" & _
" other text between hyperlinks " & _
"file://" & url2 & "" & _
"</div>"
End Sub
Note: the linked thread says you must URL-encode the links (space to %20 etc), but at least for my simple test, that wasn't necessary.
Note 2: You can't have a different display text and link url, at least I didn't get that to work.

FileSystem.WriteAllText adds non-printable characters

Here are two methods for writing text to a file in VB.Net 2012. The first one prepends the same three non-printable characters to each file: . The second one works as expected and does not add the three characters. objDataReader is an OleDB datareader.
Any idea why?
Greg
My.Computer.FileSystem.WriteAllText(lblLocation.Text & "\" &
objDataReader("MessageControlId").ToString & ".txt", objDataReader("MsgContents").ToString, False)
Using outfile As New StreamWriter(lblLocation.Text & "\" & objDataReader("MessageControlId").ToString & ".txt")
outfile.Write(objDataReader("MsgContents").ToString)
End Using
Thanks. I found the entry below I after Googled BOM, in case anyone wants a more detailed explanation. While the BOM was not visible in a text editor it did cause problems when I passed the file to our HL7 interface engine.
Greg
Write text files without Byte Order Mark (BOM)?

How to send a same reply mail (template saved in outlook) to the mail sender (to, cc)?

I am receiving continues emails from customer (different customers) to update their asset details in database.. once process done .. I have to reply (including cc) from their mail telling like "asset details successfully stored in Database" (am using template) using VBA.
Option Explicit
Public Sub ReplyToAll()
Dim oExp As Outlook.Explorer
'for selected mails in outlook
Dim oSM As mailItem
Dim oNM As mailItem
On Error GoTo Err
Set oExp = Outlook.Application.ActiveExplorer
'Check if something is selected
If oExp.Selection.Count > 0 Then
'Get the first item selected
Set oSM = ActiveExplorer.Selection.Item(1)
'Create a Reply template
Set oNM = oSM.ReplyAll
With oNM
'Change the subject
.Subject = "RE: " & oSM.Subject
'Change the body
.Body = .Body & Chr(13) & Chr(13)
'Display the new mail before sending it
.Display
End With
End If
Exit Sub
Err:
MsgBox Err.Description, vbCritical
End Sub
section 3
Sub ReplyAll()
Dim objOutlookObject As mailItem
For Each objOutlookObject In GetCurrentOutlookItems
With objOutlookObject
.ReplyAll.Display
'prob area code does not include the template saved in the location c ..throws some error
.createitemtemplate("c:\car.jtm")
End With
Next
End Sub
Function GetCurrentOutlookItems() As Collection
Dim objApp As Outlook.Application
Dim objItem As Object
Dim colItems As New Collection
Set objApp = CreateObject("Outlook.Application")
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
For Each objItem In objApp.ActiveExplorer.Selection
colItems.Add objItem
Next
Case "Inspector"
colItems.Add objApp.ActiveInspector.CurrentItem
Case Else
' anything else will result in an error, which is
' why we have the error handler above
End Select
Set objApp = Nothing
Set GetCurrentOutlookItems = colItems
End Function
I am sorry my comment was so curt; 500 characters does not leave much room for a full answer.
Your question is very unclear so it is likely to be closed. Certainly, I do not see how anyone could answer it. That is why it is important that you try to solve your own problem and return as necessary with specific questions.
Below I provide links to recent posts that I believe will help you get started. As I said in my comment, look through recent posts. Use the search facility. There are some very good answers here if you look for them.
The first two posts are tutorials written by me. The early steps are the same but, because the questions were not quite the same, later steps are different. Look at both and pick out the bits relevant to you. The others posts all contain information you may find helpful.
How to import the outlook mail data to excel
update excel sheet based on outlook mail
could anyone guide me in creating an outlook macro that does the following
send an email from excel 2007 vba using an outlook template set variables
using visual basic to access subfolder in inbox
vba outlook event moving email
New section in response to new information from questioner
Except for minor modifications, the code in your question was taken from the Microsoft Help file for NewMailEx Event. This code will only work if you have the correct type of installation and if you place it in the correct place:
"The NewMailEx event will only fire for mailboxes in Microsoft Outlook that provide notification for received message such as Microsoft Exchange Server. Also, the event will fire only if Outlook is running. In other words, it will not fire for the new items that are received in the Inbox when Outlook was not open. Developers who want to access these items for customers running Outlook on an Exchange server e-mail account need to implement their code on the server. However, the NewMailEx event will fire against Cached Exchange Mode in all settings: Download Full Items, Download Headers, and Download Headers and then Full Items."
Do you have the correct type of installation? Can you place your code on the server? Even if this is the correct approach for the final version of your macro, I do not believe it is the correct approach while you are learning VBA and Outlook.
You need two things:
a detailed specification of the macro you wish to write and
more understanding of VBA and Outlook.
I doubt you can create the detailed specification yet because you do not know enough about VBA and Outlook. But we can list things you will need to know:
How do you write to your database from Outlook?
How do you identify the mail items you wish to record? In your example, you are checking for a subject of "Hello" and replying "Hi". This is fine for a first experiment but you need to identify the real method. Is it a new sender? Is there specific information in the body of the message? Does a human have to identify such mail items?
In your example, you have a folder "Personal" under "Inbox". Many people seem to have this type of folder structure and Microsoft examples tend to use folders like this. I do not. I have a folder called "!Home". Under this I have folders for "Insurance", "Shopping", "Money". Under these I have folders for my different suppliers. Once I have dealt with a message, I move it to appropriate folder. Replies go to the same folder. This is my system and it works for me. What is your system going to be? Will, for example, there be a single folder for all customers or one per customer?
The above is a starter list of questions for your specification but it is also a starter list of things you need to know.
Perhaps you have a boss who wants you to stop wasting time and start writing the macro but you do not know enough yet to plan the final macro.
Start with my tutorials. The first three steps are about the folder structure. These steps are essential if you have the kind of complex folder structures I have. Next I go through a folder displaying selected information from each mail item. I have steps in which I write message bodies to disc. I suggest you go through both tutorials and try my code. Not all of it will be immediately useful but it is all good background information.
What is your database? Is it Access or Excel? There is some help in my tutorials and in the other links above with writing to Excel which you could adapt for Access.
I think the above is enough for now. Take it slowly and it will start to make sense. I still remember the first time I tried to write an Outlook macro so I understand your confusion. I promise that it will become clear. Best of luck.
New section in response to the following comment:
"hello i have tried ..Got what i want....Removed my previous code..and tried replaced the new code .. Now little help needed from you ....is there any way to use same format like when we click the replyall button in outlook .. my code working fine ..prob is format of the mail is differ .."
Problem 1
.Body = .Body & Chr(13) & Chr(13)
You are using the text body. I think you want the HTML body. Try:
.HTMLBody = .HTMLBody & Chr(13) & Chr(13)
Problem 2
You cannot add to the HTML body in this way. The HTML body will be:
<!doctype ...><html><head> ... </head><body> ... </body></html>
You must add your text to the beginning of the body; that is, just after <body>. If you just add your text, you will be accepting whatever style, margins and colours the sender has used. The following code adds some text that looks the same in every email I have tried it with. My text is within a table with a single cell. The table covers the full width of the page. The text is blue on a white background.
Dim InsertStg As String
Dim Inx As Long
Dim Pos As Long
'Change the body step 1: Create the string to be inserted
InsertStg = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
" bgColor=#FFFFFF><tr><td><p>"
For Inx = 1 To 10
InsertStg = InsertStg & "Sentence " & Inx & " of first paragraph. "
Next
InsertStg = InsertStg & "</p><p>"
For Inx = 1 To 10
InsertStg = InsertStg & "Sentence " & Inx & " of second paragraph. "
Next
' The following adds a signature at the bottom of the message.
' "font-family" gives a list of fonts to be tried. If these are
' missing from your computer, use the names of fonts you do have.
' "serif" means that if none of the fonts exist any serif font
' that exists is to be used.
InsertStg = InsertStg & "</p><p style = ""font-family: Mistral, " & _
"Vivaldi, serif; font-size: 14px; color: " & _
"rgb(127,0,127)"">John Smith<br>5 Acacia Avenue<br>"
InsertStg = InsertStg & "</p></td></tr></table>"
'Change the body step 2: Find insertion position just after <Body> element
Pos = InStr(1, LCase(.HTMLBody), "<body")
If Pos = 0 Then
Call MsgBox("<Body> element not found in HTML body", vbCritical)
Exit Sub
End If
Pos = InStr(Pos, .HTMLBody, ">")
If Pos = 0 Then
Call MsgBox("Terminating > for <Body> element not found in HTML body", vbCritical)
Exit Sub
End If
'Change the body step 3: Insert my text into body
.HTMLBody = Mid(.HTMLBody, 1, Pos) & InsertStg & Mid(.HTMLBody, Pos + 1)