tags:

views:

33

answers:

2

Can anyone sort out the following code to make the adding an attachment to an email work please.

Thanks

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="ISO-8859-1" Debug="true" %>
<% @Import Namespace="System.Web.Mail" %>
<% @Import Namespace="IO" %>

<script language="vb" runat="server">

Sub btnSendEmail_Click(sender as Object, e as EventArgs)

  Dim objMM as New MailMessage()

  objMM.To = "[email protected]"
  objMM.From = "[email protected]"
  objMM.BodyFormat = MailFormat.HTML
  objMM.Priority = MailPriority.Normal
  objMM.Subject = "Attachment test"
  objMM.Body = "There should be an attachment with this email"

  objMM.Attachments.Add(new MailAttachment("myimage.jpg"))

  SmtpMail.SmtpServer = "localhost"
  SmtpMail.Send(objMM)

End Sub

</script>

<html>
<head>
</head>
<body>
    <form runat="server">
        <asp:Button runat="server" id="btnSendEmail" Text="Send email" OnClick="btnSendEmail_Click" />
    </form>
</body>
</html>
+2  A: 

I'm suspicious about

new MailAttachment("myimage.jpg")

I suspect you might want to get the full path e.g.

new MailAttachment(Server.MapPath("Myimage.jpg"))
PhilPursglove
+3  A: 

The file path needs to be a full path but that aside, System.Web.Mail is deprecated/obsolete. You should be using the System.Net.Mail API, see here for examples.

annakata
+1 Good catch - I didn't even spot that...
PhilPursglove
Thanks for that... i'm new to .net so things like that are much appreciated.
Tom
OK... so it would appear that taking this piece of advice creates all manner of other errors with the TO, FROM, BodyFormat, Attachment and SMTP parts of the code... can anyone point me in the right direction to fix these new problems?
Tom
@Tom: That sounds like you're mixing the System.Net and System.Web APIs - I would suggest that you either go with the state you had previously but fix the path to the file (fastest solution but maintenance overhead for future) or copy and paste the example on MSDN and modify the parts you need to. That way would require the most coding proficiency but would be future safe. (Well as much as anything can be). If you still have problems then post your new code and we'll look at that.
annakata