VB.NET Linklabel gives 'System.NullReferenceException' - vb.net

I have a few linklabels that I use for email addresses. At run time I can click on the link and it opens a new email with the address exactly like I want it to. But when I close the email and want to click on it again it gives me the System.NullReferenceException.
I am still learning so it is likely I am making a rookie error somewhere. I understand what the error means but the label already have text data linked to it so I do not understand why it then gives the Null error on the 2nd try. Does it need to be reloaded or refreshed?
Dim reader As New IO.StreamReader(CurDir() & "\" & "AdelphiContacts.txt")
linklabel1.Text = reader.ReadLine()
With outMsg
.To = linklabel1.Text
End With
'Display email
outMsg.Display()
reader.Close()
The error comes up when I debug at
.To = linklabel1.Text
For outMsg it comes from
Dim outApp As Application = New Application
Dim outMsg As MailItem = outApp.CreateItem(OlItemType.olMailItem)

Related

Activate specific URL contained in an email message

I know virtually nothing about VBA but am attempting to learn. I am trying to assist a blind client who gets messages from a specific agency he uses to get freelance engagements. These messages have to be responded to almost instantly by clicking on an "Accept" link in the message or there is no chance of getting the job. Since he uses a screen reader this complicates matters.
I have tried to adapt what I've found at stackoverflow to take the message on receipt, triggered by a message rule, to invoke VBA code to dig out the URL and immediately activate it.
Sub LaunchURL(itm As MailItem)
Dim MsgBody As String
Dim AllMsgLines
Dim IndividualLine
Dim AllLineWords
Dim SingleWord
Dim MboxReply
MsgBody = itm.Body
AllMsgLines = Split(MsgBody, vbCrLf)
For Each IndividualLine In AllMsgLines
AllLineWords = Split(IndividualLine, " ")
For Each SingleWord In AllLineWords
If SingleWord Like "http://*" Then
MboxReply = MessageBox.Show("I've found a URL", "LaunchURL Script", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk)
Set itm = Nothing
Exit Sub
End If
Next SingleWord
Next IndividualLine
Set itm = Nothing
End Sub
Private Sub TestLaunchURL()
Dim currItem As MailItem
Set currItem = ActiveInspector.CurrentItem
LaunchURL currItem
End Sub
The code above is what I've been experimenting with. I will actually replace the message box either with:
Shell ("C:\Program Files\Internet Explorer\IEXPLORE.EXE" & " " & SingleWord)
or
FollowHyperlink SingleWord
When I run this I get "Runtime Error 91: Object variable or With block variable not set". I've tried stepping into the code and from what I can tell the problem originates at the SET statement in the TestLaunchURL subroutine.
I am trying to snag the message I currently have focus on in my Outlook inbox and parse it apart for the first instance of "http://", at least at the moment.
Also, what would I expect to be getting back in "SingleWord" if I have a URL that has click-through text that is shown to the user tied to the actual URL itself? I might be able to exploit that to look for the word "Accept" just ahead of the URL itself were "Accept" the click through text.

Send Outlook Email with Table in VB.net

I'm using the following code to generate and open an Outlook E-Mail. However I need to be able to insert a table with some variables and my current method only allows for basic text, could anyone suggest a way in which I could integrate a table?
Try
lblStatus.Text = "Opening OutLook Mail, Please Wait..."
My.Application.DoEvents
Dim Outl As Object
Outl = CreateObject("Outlook.Application")
If Outl IsNot Nothing Then
Dim omsg As Object
omsg = Outl.CreateItem(0)
omsg.body = "Table should go here"
omsg.To = "*address goes here"
omsg.subject = SubjectLine
'set message properties here...'
omsg.Display(false) 'will display message to user
lblStatus.Text = "Outlook Mail Template Opened."
My.Application.DoEvents
End If
Catch ex As Exception
lblStatus.Text = "Opening OutLook Mail | Error Encountered"
My.Application.DoEvents
'log error
End Try
Here's an example of what the table needs to be like:
Obviously there's formatting code used by Outlook, but I don't know how to send that from visual basic into the email.
First get the DoEvents() out of your code. They are not helping anything.
As for the table, the simplest way to do it is to build the message body as a HTML string that includes the table. Of course, that requires the receiver of the email set to accept HTML.

Lotus Notes VBA Email Automation - db.CreateDocument Command Fail

I'm trying to automate the sending of an email through Lotus Notes 9.0 using VBA. The code will load up notes, which asks for my password but before the password prompt shows up, I get an error. The error I run in to is "Run-time error '-2147417851 (80010105)': Automation Error The server threw an exception" When I hit debug, the line that it fails on is "Set obDoc = obDB.CreateDocument". A lot of what I've seen online example wise matches what I'm doing in my code, so I'm not sure where the problem is.
Here's the code:
Sub Send_Emails()
Dim stSubject As Variant
Dim emailList As Variant
Dim obSess As Object
Dim obDB As Object
Dim obDoc As Object
'----Create Email List - separate function, dynamically creates email list based off report processing done in other functions
CreateEmailList
'----Info for Subject
stSubject = "test subject"
'----Create Notes Session
Set obSess = CreateObject("Notes.NotesSession")
Set obDB = obSess.GETDATABASE("", "")
If obDB.IsOpen = False Then
Call obDB.OPENMAIL
End If
'----Create the e-mail - **FAILURE OCCURS HERE**
Set obDoc = obDB.CreateDocument
'----Add values to the email
With obDoc
.form = "Memo"
.SendTo = "test#test.com"
.blindcopyTo = emailList
.Subject = stSubject
.HTMLBody = "<HTML><BODY><p>test</p></BODY></HTML>"
.SaveMessageOnSend = True
.PostedDate = Now()
.Send 0, emailList
End With
'----Clean Up
Set obDoc = Nothing
Set obDB = Nothing
Set obSess = Nothing
MsgBox "The e-mail has been sent successfully", vbInformation
End Sub
You mention that you are using Notes 9, so I looked at the online help for Notes 9.01 and the help page for the OpenMail method says
Note: This method is supported in LotusScript® only. For COM, use OpenMailDatabase in NotesDbDirectory.
Now, you're actually using the OLE automation classes (rooted at Notes.NotesSession), not the COM classes (rooted at Lotus.NotesSession), so I don't know if you can use the NotesDbDirectory class or not, but the other way of opening the current user's mail database would be to call NotesSession.GetEnvironmentString("MailServer",true) and NotesSession.GetEnvironmentString("MailFile",true), and use those as the values for your call to GetDatabase.

Getting "Object variable or With block variable not set" on first use of document.TypeText with Outlook Message

Can anyone help me figure out what's going wrong and how to fix it?
I'm trying to automate sending an email with some daily status information. I'd tried automating this from Access but kept running into (known but apparently unsolved) problems with GetObject(, "Outlook.Application") with Windows 8.1 64 and Outlook 2013. So I decided to automate starting from Outlook.
Anyway, I moved the mail message creation code into Outlook vba and had it start Access and run the Access code. This is all well and good until I get to creating the mail message. Everything starts just fine until it gets to writing to the body of message (using Word as the body editor). At the first "TypeText" command, I'm getting the error message in the title. If I click debug on the error notification dialog and then single-step through the line of code in question, it works just fine. I thought that there was some timing problem, so I stuck a 2-second wait in the code. No luck. The code in question, with some other oddities associated with testing (notably trying to type and then delete text), is below:
Public Sub CreateMetrics()
' Mail-sending variables
Dim mailApp As Outlook.Application
Dim accessApp As Access.Application
Dim mail As MailItem
Dim wEditor As Word.Document
Dim boolCreatedApp As Boolean
Dim i As Integer
Set mailApp = Application
' Create an Access application object and open the database
Set accessApp = CreateObject("Access.Application")
accessApp.OpenCurrentDatabase dbLoc
accessApp.Visible = True
' Open the desired form and run the click event hander for the start button
accessApp.DoCmd.OpenForm ("ProcessStatus")
accessApp.Forms![ProcessStatus].StartButton_Click
' Create the outgoing mail message
Set mail = Application.CreateItem(olMailItem)
mail.Display
mail.BodyFormat = olFormatHTML
Set wEditor = mailApp.ActiveInspector.WordEditor
With accessApp.Forms![ProcessStatus]
Debug.Print .lblToList.Caption
Debug.Print .lblSubject.Caption
Debug.Print .lblIntroduction.Caption
Debug.Print .lblAttachFilepath.Caption
End With
mail.To = accessApp.Forms![ProcessStatus].lblToList.Caption
mail.Recipients.ResolveAll
mail.Subject = accessApp.Forms![ProcessStatus].lblSubject.Caption
mail.Attachments.Add accessApp.Forms![ProcessStatus].lblAttachFilepath.Caption
Sleep 2000
' Error occurs in the next line ***********************************************
wEditor.Application.Selection.TypeText Text:="Test"
wEditor.Application.Selection.HomeKey
wEditor.Application.Selection.Delete Count:=4
wEditor.Application.Selection.PasteSpecial DataType:=wdPasteBitmap
wEditor.Application.Selection.HomeKey
wEditor.Application.Selection.TypeText accessApp.Forms![ProcessStatus].lblIntroduction.Caption
wEditor.Application.Selection.TypeText Text:=Chr(13) & Chr(13)
wEditor.Application.Selection.EndKey
' wEditor.Application.Selection.EndKey
' wEditor.Application.Selection.TypeText Text:=Chr(13)
' wEditor.Application.Selection.TypeText Text:=configs("EmailSignature")
' End With
With mailApp.Session.Accounts
i = 1
Do While i <= .Count
' Use either the specified email address OR the last outlook email address
If RegEx_IsStringMatching(.Item(i).SmtpAddress, accessApp.Forms![ProcessStatus].lblSenderRegex.Caption) Or i = .Count Then
mail.SendUsingAccount = .Item(i)
i = .Count + 1
Else
i = i + 1
End If
Loop
End With
mail.Save
accessApp.Quit
End Sub
I added a "mail.Display" just before the line that was causing the failure, which seemed, incorrectly, to have fixed the problem.
I have now solved this problem by executing a document.select on the document associated with the email I was creating. To select the right document (there doesn't seem to be any guarantee of which one that would be within the wEditor.Application.Documents collection, though it was typically the first one), I created an almost-certainly unique piece of text and assigned it to the body of the email, which I could then go and find. Here's the new code that I added to the code above:
Dim aDoc As Word.Document
Dim strUniqueID As String
. . .
mail.Attachments.Add accessApp.Forms![ProcessStatus].lblAttachFilepath.Caption
strUniqueID = accessApp.Forms![ProcessStatus].lblSubject.Caption & Rnd(Now()) & Now()
mail.Body = strUniqueID
' Search for the unique text. aDoc.Content has extra characters at the
' end, so compare only for the length of the unique text
For Each aDoc In wEditor.Application.Documents
If Left(aDoc.Content, Len(strUniqueID)) = strUniqueID Then
aDoc.Select
mail.Body = ""
End If
Next aDoc
wEditor.Application.Selection.TypeText Text:="Test"
. . .
I looked at a lot of examples of code that did this kind of thing. None of them performed a select or said anything about needing one. Debugging was made that much harder because the select occured implicitly when the debugger was invoked.

How to send mail without asking a sender account for permission?

I'm trying to make a VB.NET app that sends a mail to a certain email account, that account's domain is not gmail,hotmail,etc. it belongs to the company where I work.
My problem is, Outlook prompts a warning that says "a program is attempting to send email on your behalf..." and it requires a click to send the mail(that's because it is using the current PC user account to send the mail). I need to make it automatized(no clicks required)
Since this is the first time I do this kind of thing, I must ask if there is a way to send the mail without a sender account? So I don't need to ask for permission to send the mail nor write any password in the code. Or if it is not possible at least a way to make my .exe "trusted" for any PC inside the company where it is executed.
What lines do I have to change in my code to skip that message?
Dim OutApp As Object
Dim OutMail As Object
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim date As String
Dim proc As System.Diagnostics.Process
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
If proc.MainWindowTitle.Trim.Length = 0 Then
proc.Kill()
End If
Next
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open("\\file.xlsm")
xlWorkSheet = xlWorkBook.Worksheets("sheet")
Try
xlWorkSheet.Range("E4").Select()
xlWorkSheet.Range("E4").Activate()
date = xlApp.ActiveCell.Value
Do While Convert.ToString(xlApp.ActiveCell.Value) <> ""
'The mail part start here
If (DateTime.Today - CDate(date)).Days = 180 Then
OutApp = CreateObject("Outlook.Application")
OutMail = OutApp.CreateItem(0)
'On Error Resume Next
With OutMail
.To = "xxxx#xxxx.com"
.CC = ""
.BCC = ""
.Subject = "subject"
.Body = "text"
.Send()
End With
' On Error GoTo 0
OutMail = Nothing
OutApp = Nothing
End If
xlApp.ActiveCell.Offset(1, 0).Select()
date = xlApp.ActiveCell.Value
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
This is a console app, so there is no web.config here.
Please help.
You can try third party email service providers like Amazon SES, SendGrid, etc. Then using SMTP or APIs provided by them you can send mail from any email address but note that you need to authorize the email address just one time.
They generally send an email with a link to an email address and you just need to click on it to authorize that address.