Solved

Specified cast is not valid error in sending e-mail with asp.net

Posted on 2003-12-11
21
3,738 Views
Last Modified: 2012-05-04
I am trying to send an e-mail with  file attachement using asp.net. I keep getting an error System.InvalidCastException: Specified cast is not valid in this line:
SMTPMail.Send(myMail)

How do I fix that?

Here is my code:

Sub Page_Load(source as Object, e as EventArgs)
     Dim myDate as DateTime = DateTime.Now
     Dim myLabel as Label
     Dim myUser as Label
     Dim sNTUser, strTemp, sNTUserDomain
     Dim myStr as String
     myUser=Page.FindControl("lblUser")
     
     sNTUserDomain =Request.ServerVariables("LOGON_USER")
     'to get rid of the domain  
     strTemp = InStr (sNTUserDomain,"\")
     sNTUser = Mid(sNTUserDomain, strTemp+1)
     myUser.Text=sNTUser

     myLabel=Page.FindControl("lblDate")
     myLabel.Text = myDate.ToShortDateString()
     
     '***
     If Page.IsPostBack Then
          Dim myMail As New MailMessage()
          myMail.To="me@test.com"
          myMail.From=sNTUser & "@test.com"
          myMail.Subject="test"
          myMail.BodyFormat=MailFormat.Text
          myMail.Body=txtComments.value
     
          If Not (file1.PostedFile Is Nothing) Then
               'get the attachment
               Dim myFile As New FileInfo(file1.PostedFile.FileName)
               
               myMail.Attachments.Add(myFile)
          End If
     
          SmtpMail.SmtpServer = "MYSERVER"
          SMTPMail.Send(myMail)
     End If
End Sub

</script>


..................
<form runat="server">
<asp:TableRow>
     <asp:TableCell width="20%">
                                                    <font size="2">Attachment:</font>
                                        </asp:TableCell>
                                        <asp:TableCell width="80%">
                                                       <input type="file" id="file1" runat="server">
                                        </asp:TableCell>
</asp:TableRow>
</asp:Table>
<br>
<asp:Button id="b1" Text="Submit" runat="server" />
</form>



0
Comment
Question by:YZlat
21 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9920814
Dim myFile As New MailAttachment(file1.PostedFile.FileName)
0
 
LVL 4

Expert Comment

by:krznpsk
ID: 9920816
Try fully qualifying the names of your classes, using
Dim myMail as New System.Web.MailMessage
System.Web.Mail.SmtpMail.Send(myMail)

0
 
LVL 35

Author Comment

by:YZlat
ID: 9920935
krznpsk, I already tried that
0
 
LVL 35

Author Comment

by:YZlat
ID: 9920949
TheLearnedOne, now I get an error System.Web.HttpException: Invalid mail attachment 'C:\test.doc'.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9920972
Make sure the file permissions are set on the file so that the ASPNet user has read access.
0
 
LVL 35

Author Comment

by:YZlat
ID: 9920976
and permissions to this file allow everyone the full control
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9921104
I set up a small test on my development PC (Windows XP, IIS, ASP.NET test app, VS.NET 2003), and this worked fine.  E-Mail was sent.  Usually the HttpException is really a 'File not found' exception.
0
 
LVL 35

Author Comment

by:YZlat
ID: 9921155
It does not say file not found, it says Invalid mail attachment.
can you post all the code from your test?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9921941
   Dim myMail As New MailMessage
         myMail.To = "<address>"
         myMail.From = "<address>"
         myMail.Subject = "test"
         myMail.BodyFormat = MailFormat.Text
         myMail.Body = "This is a test"

         Dim myFile As New MailAttachment("c:\Temp\test.txt")
         myMail.Attachments.Add(myFile)

      SmtpMail.SmtpServer = "<server>"

         SMTPMail.Send(myMail)

Look at this:
Matthew Reynolds' .NET 247 Newsgroup - Invalid mail attachment
http://www.dotnet247.com/247reference/msgs/22/113371.aspx
0
 
LVL 35

Author Comment

by:YZlat
ID: 9922545
TheLearnedONe, I tried that already
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 96

Expert Comment

by:Bob Learned
ID: 9922617
I haven't had many problems with mail attachments, so bear with me here.  Not a lot of references on that specific error, other than file not found or access rights.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9922657
This may also be because the file is in use by another application.  I tried that with my test setup, and got the 'Invalid mail attachment' error.
0
 
LVL 35

Author Comment

by:YZlat
ID: 9922912
have you ever used Outlook with VB.NET?  
0
 
LVL 35

Author Comment

by:YZlat
ID: 9923110
I've modified my program to send e-mail with attachment via Outlook. I added a reference toMS Outlook 9.0 but I still get an error "System.Runtime.InteropServices.COMException: COM object with CLSID {0006F03A-0000-0000-C000-000000000046} is either not valid or not registered."

Here is my code;

<script language="vb" runat="server">
Sub Page_Load(source as Object, e as EventArgs)
      Dim myDate as DateTime = DateTime.Now
      Dim myLabel as Label
      Dim myUser as Label
      Dim sNTUser, strTemp, sNTUserDomain
      Dim myStr as String
      myUser=Page.FindControl("lblUser")
      
      sNTUserDomain =Request.ServerVariables("LOGON_USER")
      'to get rid of the domain  
      strTemp = InStr (sNTUserDomain,"\")
      sNTUser = Mid(sNTUserDomain, strTemp+1)
      myUser.Text=sNTUser

      myLabel=Page.FindControl("lblDate")
      myLabel.Text = myDate.ToShortDateString()
      
      '***
           If Page.IsPostBack Then
      Dim objOutlook As Outlook.Application= New Outlook.ApplicationClass()
      Dim objMail As Outlook.MailItem
      ' Create an instance of the Attachment
      Dim oAttach As Outlook.Attachment

      objMail= objOutlook.CreateItem(Outlook.OlItemType.olMailItem)    

      objMail.To = "test@test.com"
      objMail.Subject = "sample email"
      objMail.HTMLBody = "Hi,\nI'm your sample email."
      If (file1.PostedFile.FileName = "") Then
            MsgBox ("You did not attach a file")
      Else
            'Attach the file Path to the Mail Item
            objMail.Attachments.Add(file1.PostedFile.FileName)
End If
            objMail.Display()
     ' CType(objMail,Outlook._MailItem).Send()
     ' objMail.Send()

            objOutlook = Nothing
      End If
End Sub
</script>
0
 
LVL 35

Author Comment

by:YZlat
ID: 9923113
I get the error in line
Dim objOutlook As Outlook.Application= New Outlook.ApplicationClass()
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 100 total points
ID: 9923275
Is Outlook installed on the server?
0
 
LVL 35

Author Comment

by:YZlat
ID: 9929054
I checked the registry and the class id for the outlook is not there:(
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9929063
You might want to reinstall Outlook on the server.
0
 
LVL 35

Author Comment

by:YZlat
ID: 9929358
they would not let me install outlook on the server
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 9929369
Well, you may have to go back to the SMTPMail solution, and try to figure out what the problem is, since that doesn't require anything other than the framework installed on the machine.
0
 

Expert Comment

by:gulltop
ID: 11885769
I had this problem too, and tried all the usual stuff (permissions, valid path, etc) in other suggestions.  

I was using both System.IO.StreamWriter and Scripting.FileSystemObject to create the file before attaching it.  I figured out that you have to .Close() the file before you can attach it, or it will stay locked and give you a "Invalid mail attachment" error.

like so...
    DIM f as System.IO.StreamWriter
    f = System.IO.File.CreateText(strFileFullPath)
    f.Write(strBody)
    f.Close()    '--- important part, unlocks file
    f = nothing

Hope it helps someone.
-Rob
http://slingfive.com/
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now