Solved

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

Posted on 2003-12-11
21
3,746 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
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

 
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
 
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
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 shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

830 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