VB.Net Hyperlinking in EWS email with class properties - vb.net

I need help getting the hyperlink to work as well as getting the value stored in YestFile.FileName to show up.
I have a list of objects of class FileFromYesterday (Collection2) with 3 properties. Two properties are just Strings (FileName and Entity) but one property (URL) contains a URL as a String. I am trying to hyperlink the URL to FileName in the main.
I have a feeling that I need to use HTML to format the email somehow but I have no Idea where to begin
Dim HyperLink As String
Dim FileLine As String
Dim NewBody As String
Dim message As New EmailMessage(EWS)
message.Subject = "Monthly Financial Imported into Docushare on " & String.Format("{0:MM-dd-yyyy}", Yesterday)
NewBody = "Total of " & Collection2.Count & " Files Imported." & "\n"
For Each YestFile In Collection2
HyperLink = YestFile.FileName.Replace(".pdf", "")
FileLine = HyperLink & "Entity: " & YestFile.Entity & Environment.NewLine
NewBody = NewBody & FileLine
Next

You should be creating a HTML document in your NewBody varible so you need the pre and post tags for a HTML document eg
<html>
<body>
</body>
</html>
the body content you want should go within between the Body Tags and for thing like NewLines you need to use the appropriate HTML tags such as
<br />
Eg what ever you end up creating in you NewBody variable you should be able to write out to a file or test in any Online HTML validator https://validator.w3.org/#validate_by_input to see if its valid and how it will look before trying to send it.

Related

Uploading File To Website

I am still a beginner with VBA, so if you need further explanation or I am not describing my problem correctly please let me know.
I am trying to achieve the following:
Upload a file from my computer to a website (You can only try to upload if you login, so sadly I cannot share a link)
In order to achieve this I need to do three things:
1) Click the "Upload" Button
2) Insert the Filepath into the search field of the PopUp Window
3) Click the "Open" Button
The website looks like this:
The PopUp Window looks like this:
The HTML code of the upload field is the following:
<div class="button-wrapper">
<input class="design-file-input" type="file">
<a class=" button prio1" href="javascript:void(0);">Design hochladen</a>
</div>
I guess there might be two solutions two my problem, however, I am not able to realize my plans.
IDEA 1
Somehow get the filepath into the input field and the page to download it
Therefore I tried the vba following VBA codes:
objIE.document.getElementsByClassName("design-file-input")(0).Value
objIE.document.getElementsByClassName("design-file-input")(0).innerText
And then try to somehow make the website submit my entry.
IDEA 2
Click the "Design Hochladen" Button.
objIE.document.getElementsByClassName("button-wrapper")(0).Click
But then the PopUp window comes up and I don't know how to control it with VBA
I am happy to hear and try your suggestions!! If you need any further details, just let me know! Thank you so much if you can give me any advice
Directly assigning the file path to the value of that specific HTML element does not work. A while ago, I had the same issue (automatically passing a file to an upload file dialog). After a long googling session, I found following solution. Unfortunately, I could not find the link from where I took this answer. In case I come accross the website, I will share the link with you:
Dim FilePath As String
Dim FileName As String
FilePath = Environ$("temp") & "\"
FileName = "test_file_for_upload" & ".xlsx"
UploadFile DestURL, FilePath & FileName, "file" 'Usage
'******************* upload - begin
'Upload file using input type=file
Public Sub UploadFile(DestURL As String, FileName As String, _
Optional ByVal FieldName As String = "File")
Dim sFormData As String, d As String
'Boundary of fields.
'Be sure this string is Not In the source file
Const Boundary As String = "---------------------------0123456789012"
'Get source file As a string.
sFormData = GetFile(FileName)
'Build source form with file contents
d = "--" + Boundary + vbCrLf
d = d + "Content-Disposition: form-data; name=""" + FieldName + """;"
d = d + " filename=""" + FileName + """" + vbCrLf
d = d + "Content-Type: application/upload" + vbCrLf + vbCrLf
d = d + sFormData
d = d + vbCrLf + "--" + Boundary + "--" + vbCrLf
'Post the data To the destination URL
IEPostStringRequest DestURL, d, Boundary
End Sub
'sends URL encoded form data To the URL using IE
Sub IEPostStringRequest(URL As String, FormData As String, Boundary As String)
'Create InternetExplorer
Dim WebBrowser: Set WebBrowser = CreateObject("InternetExplorer.Application")
'You can uncoment Next line To see form results
WebBrowser.Visible = True
'Send the form data To URL As POST request
Dim bFormData() As Byte
ReDim bFormData(Len(FormData) - 1)
bFormData = StrConv(FormData, vbFromUnicode)
WebBrowser.navigate URL, , , bFormData, _
"Content-Type: multipart/form-data; boundary=" + Boundary + vbCrLf
Do While WebBrowser.Busy
' Sleep 100
DoEvents
Loop
'WebBrowser.Quit
End Sub
'read binary file As a string value
Function GetFile(FileName As String) As String
Dim FileContents() As Byte, FileNumber As Integer
ReDim FileContents(FileLen(FileName) - 1)
FileNumber = FreeFile
Open FileName For Binary As FileNumber
Get FileNumber, , FileContents
Close FileNumber
GetFile = StrConv(FileContents, vbUnicode)
End Function
'******************* upload - end
The third argument "file" denotes the ID of the HTML element which needs to be triggered.
Hope this solution workds for you as well

Minify HTML code into one line

My program is generating HTML code, which is placed afterwards into some string variable. This HTML code is ready to be placed in CSV file, so the entire code is surrounded by quotes, as well as all inner double quotes have additional quotes for escape. The result is the user can see it nicely formatted in output.
However, I have to convert this code to one line as assuming that my excel having trouble with this 'well formatted' HTML code as there are line-breaks. Therefore, I want before I place into CSV to make this HTML code into one line. Can you tell me how to achieve that?
You can replace line breaks by nothing to get a single lined output:
Dim TestString As String
TestString = " <body>" & vbCrLf & " some html" & vbCrLf & " </body>"
Dim SingleLined As String
SingleLined = Replace(TestString, vbCrLf, "")

Find and Replace specific string in Outlook message

My code basically searches for the string "#XX" in the email body. The "#XX" is usually followed by a text like "#XXApple". And this "#XXApple" can be seen multiple times in the email message.
The code below works in such a way that it only replaces the first hit with spaces. However, the rest of the "#XXApple" will only be changed to "Apple"
Is there a way where I can do a "Find and Replace All" in Outlook?
obj.HTMLBody = Replace(obj.HTMLBody, "#XX", " ", 15)
Not tested or verified but this is the general idea of what I meant to say in the comment above.
Dim Cet
Dim TesPos As Int, i As Int
Cet = Split(obj.HTMLBody, " ")
For i=LBound(Cet) to Ubound(Cet)
TestPos = 5
TestPos = InStr(1,Cet(i), "#XX", CompareMethod.Text)
if TestPos = 1 then
Cet(i) = ""
Else: End if
Next i
obj.HTMLBody = ""
For i=LBound(Cet) to Ubound(Cet)
obj.HTMLBody = obj.HTMLBody & " " & Cet(i)
Next i
Debug.Print obj.HTMLBody
The Outlook object model provides three main ways for working with item bodies:
Body - a string representing the clear-text body of the Outlook item.
HTMLBody - a string representing the HTML body of the specified item.
Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to set up the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies. It us up to you which way is to choose to deal with the message body. But the Word object model provides all the required methods to get the job done.

VCS File description in html

we have created a vcs file using the following code.
Dim mstream As New MemoryStream
Dim writer As New StreamWriter(mstream)
writer.AutoFlush = True
GetvCalendarText(writer)
Response.Clear()
Response.AppendHeader("Content-Disposition", "attachment; filename=Event" & eventID & ".vcs")
Response.AppendHeader("Content-Length", mstream.Length.ToString)
Response.ContentType = "application/download"
Response.BinaryWrite(mstream.ToArray)
Response.End()
GetCalendarText method
Dim body As String = <b>New event</b>
writer.WriteLine("BEGIN:VCALENDAR{0}", vbCrLf)
writer.WriteLine("VERSION:1.0{0}", vbCrLf)
writer.WriteLine("BEGIN:VEVENT{0}", vbCrLf)
writer.WriteLine("DTStart:{0}{1}", DateTime.Now.ToString("yyyyMMddTHHmm00Z"), vbCrLf)
writer.WriteLine("DTEnd:{0}{1}", DateTime.Now.AddHours(2).ToString("yyyyMMddTHHmm00Z"), vbCrLf)
writer.WriteLine("DESCRIPTION:{0}", body)
writer.WriteLine("X-ALT-DESC;FMTTYPE=text/html:{0}", body)
writer.WriteLine("SUMMARY;ENCODING=QUOTED-PRINTABLE:{0}{1}", Test event, vbCrLf)
writer.WriteLine("PRIORITY:3{0}", vbCrLf)
writer.WriteLine("END:VEVENT{0}", vbCrLf)
writer.WriteLine("END:VCALENDAR{0}", vbCrLf)
It is generating the vcs file and upon opening the file it is opening in Outlook 2010 with subject , start time and end time with correct values.
The description we have given is in html format but it is shown as plain text.
So how we can show the html description as such.
I tried to add html description in vCalendar format and can't find any proper method to do this.
Finally changed our vCalendar format to iCalendar and it allows to show html description.
We removed the description line ie writer.WriteLine("DESCRIPTION:{0}", body)
and now it showing html formatted description.
Following parts also changed.
Response.AppendHeader("Content-Disposition", "attachment; filename=Event" & eventID & ".ics")
and
writer.WriteLine("VERSION:2.0{0}", vbCrLf)

Forward an email and append additional text without losing format of original message

I'm trying to forward an email that I received and append an additional message on top of it. The following code I wrote kinda does this, but I lose all the formatting of the original message. Is there any way to maintain the format of the original message and yet able to append additional test to the email?
MY CODE:
Sub xForward()
myMessage = "You recently requested access to the table. We are requiring all requests to complete a mandatory training session." & vbCr & vbCr & "Thank you, " & vbCr & "Ricky"
Dim itmOld As MailItem, itmNew As MailItem
Set itmOld = ActiveInspector.CurrentItem
Set itmNew = itmOld.Forward
itmNew.Body = myMessage & vbCr & vbCr & itmOld.Body
itmNew.Subject = "Access Request"
itmNew.Display
Set itmOld = Nothing
Set itmNew = Nothing
End Sub
If I don't update the body of itmNew, then I maintain the format of the original message. The moment I update itmNew.Body, then itmOld.Body is written in simple text and I lose all the formatting.
I think JP's comment points you in the right direction but I assume your questions results from limited knowledge of HTML. This is not a complete tutorial on HTML but I hope it gets your started.
If you use Debug.Print to output .HTMLBody to the immediate window you will see something like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
xmlns="http://www.w3.org/1999/xhtml"> <head>
Lots of stuff here
</head> <body>
Lots of stuff here
</body> </html>
You will only get "<!DOCTYPE html ... " if the package that created the message supports the XML version of HTML. The minimum you should see is:
<html><head> Lots of stuff here </head><body> Lots of
stuff here </body></html>
If you place your extra message in front or at the end of this then you are breaking the rules of HTML. What happens will depend on how forgiving the receiver's email package is. To conform to the rules of HTML, you must place your extra message somewhere between "<body>" and "</body>".
If you look through a few messages, you will see how much they can vary. Some will be black text on white, some white text on black with every variation in between. Your message must be readable no matter what the message's authors have done. My suggestion is you create a one cell table at the top and you set the font and background colours. Try the following and then adapt it to your requirements:
Dim AddedMsg As String
Dim Pos As Long
' Create message to be inserted
' =============================
' Start a table with white background and blue text
AddedMsg = "<table border=0 width=""100%"" style=""Color: #0000FF"" bgColor=#FFFFFF>"
' Add row with single cell
AddedMsg = AddedMsg & "<tr><td><p>Cool stuff you must see!!</p></td></tr>"
' End table
AddedMsg = AddedMsg & "</table>"
' Code to add message once you have checked there is an HTML body
'================================================================
Pos = InStr(1, LCase(.HTMLBody), "<body")
If Pos = 0 Then
' This should be impossible.
Call MsgBox("<Body> element not found in HTML body", vbCritical)
' Code to handle impossible situation
End If
Pos = InStr(Pos, .HTMLBody, ">")
If Pos = 0 Then
' This should be impossible.
Call MsgBox("Terminating > for <Body> element not found in HTML body", vbCritical)
' Code to handle impossible situation
End If
'Insert your message
.HTMLBody = Mid(.HTMLBody, 1, Pos) & AddedMsg & Mid(.HTMLBody, Pos + 1)