Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2003-12-11
21
Medium Priority
?
3,769 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…

877 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