Solved

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

Posted on 2003-12-11
21
3,759 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
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
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

Containers & Docker to Create a Powerful Team

Containers are an incredibly powerful technology that can provide you and/or your engineering team with huge productivity gains. Using containers, you can deploy, back up, replicate, and move apps and their dependencies quickly and easily.

Question has a verified solution.

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

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

636 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