Question

Can anyone take a look at my code below and recommend how I can stop receiving the dreaded error 91. Error: Object variable or With block variable not set. I am using the mailto: function to send an email using the native email client and populating the email w/ data from a gridview. After the error pops up, I simply click ok and the email is loaded w/ the exact data I want!

Protected Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged, GridView1.SelectedIndexChanged
    Dim MailFormat, Number, BodyOfEmail, FullName As String
    Dim RowValue As Double

    RowValue = GridView1.SelectedDataKey.Value - 1
    Number = GridView1.Rows(RowValue).Cells(5).Text.ToString
    FullName = GridView1.Rows(RowValue).Cells(25).Text.ToString
    BodyOfEmail = “SomeTextInTheBody”
    MailFormat = "mailto:" & Number & "?" & "subject= A subject here" & "&body=" & BodyOfEmail
    System.Diagnostics.Process.Start(MailFormat)
End Sub

I can execute the following code from the .aspx page just fine:

a href="mailto:someone@example.com?Subject=Hello%20again"

and outlook opens without issue. It appears to only be an issue when the aspx.vb code up at the top is executed...

Thanks

Was it helpful?

Solution

<a href="mailto:xxx"/> works fine because it is executing in the user's browser, and will use the user's locally-installed interactive email application, whatever it happens to be.

Process.Start("mailto:xxx") will always fail because it is executing on the web server, which will probably not have a locally-installed interactive email application available, and even if it did, you would not be able to start it interactively on a desktop that does not exist. The fact that it happens to throw error 91 in your test environment is irrelevant. Don't do it, full stop.

What you need to do is arrange for a bit of JavaScript to execute on page render after the server-side event has completed. Something like location.href = "mailto:xxx" may do the trick. Exactly where you should insert this depends on your page design.

Alternatively, if you want to keep the email generation code entirely on the server-side, and you know that your users will always be using Outlook, you could look at calling Exchange Server directly. See here for a starting point.

OTHER TIPS

Have you considered using the SmtpClient class?

Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New Net.NetworkCredential("sender address", "sender password")
SmtpServer.Port = 587              'If sending from gmail...
SmtpServer.Host = "smtp.gmail.com" 'If sending from gmail...
mail = New MailMessage()
mail.From = New MailAddress("sender address")
mail.To.Add("recipient address")
mail.Subject = ""
mail.Body = ""
SmtpServer.Send(mail)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top