Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2003-12-11
21
Medium Priority
?
3,762 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

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

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

719 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