Sending email with attachment

I am looking for a way to send an email from an asp.net web app with form data in it and with an attachment. I need the user to be able to press a browse button on the upload form to browse their local hardrive to select a file, have an error message if the file is not successful, and send an email with the file as an attachment and the other form data if it is successful. This is an ASP.NET form and C# is the language that I am using. Since this will not be uploaded to a server, but instead will be sent as an email attachment, I probably will not need map path functionality.

Thanks in advance.
LVL 9
BobHavertyComhAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RouchieCommented:
You can use the InputStream to avoid having to save the file.  Go to the end of this tutorial for a full working code sample
http://www.codepal.co.uk/show/Sending_Email_Attachments_From_a_FileUpload_Control_Sends_Empty_Files
0
RouchieCommented:
In fact forget that here you go:

' create a reference to the SMTP server first so we can send after each email is created '
Dim mc As New System.Net.Mail.SmtpClient("127.0.0.1", 25)
mc.UseDefaultCredentials = False
mc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network
mc.Credentials = New System.Net.NetworkCredential("me@mydomain.co.uk", "MyPassword")

' send the first email '
Dim mm As New MailMessage
mm.To.Add(New MailAddress("me@mydomain.co.uk"))
mm.From = New MailAddress("me@mydomain.co.uk", "An ASP.NET Web Page")
mm.Subject = "Your file and password"
mm.Attachments.Add(New Attachment(fu.PostedFile.InputStream, fu.FileName))
mm.Body = "Here is your file.  Your password is xyz1234"
mc.Send(mm)

mm.Dispose()
mc.Dispose()

Open in new window


There are some gotchas if you find that .DAT attachments are being sent, or sending to multiple people as separate emails.  Post here if you find that happens.
0
BobHavertyComhAuthor Commented:
Hi Rouchie, thanks for the response and sorry for my delayed response. I am coding in C# as I mentioned, but that's okay, I can probably translate this as it is merely different syntax, but the objects are probably the same. There will be no .dat files. What I did not see is the mechanism for someone to choose the file to send as the attachment. The front end part is missing.

Thanks again.
0
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

RouchieCommented:
Please translate the code here in future if you need to:  http://converter.telerik.com/

// create a reference to the SMTP server first so we can send after each email is created
System.Net.Mail.SmtpClient mc = new System.Net.Mail.SmtpClient("127.0.0.1", 25);
mc.UseDefaultCredentials = false;
mc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mc.Credentials = new System.Net.NetworkCredential("me@mydomain.co.uk", "MyPassword");

// send the first email 
MailMessage mm = new MailMessage();
mm.To.Add(new MailAddress("me@mydomain.co.uk"));
mm.From = new MailAddress("me@mydomain.co.uk", "An ASP.NET Web Page");
mm.Subject = "Your file and password";
mm.Attachments.Add(new Attachment(fu.PostedFile.InputStream, fu.FileName));
mm.Body = "Here is your file.";
mc.Send(mm);

mm.Dispose();
mc.Dispose();

Open in new window


The front end only requires a FileUpload control with ID of "fu" and a send button that fires the code above.

I didn't realise that you're probably starting with nothing, so make sure that the address of your mail host replaces my value of "127.0.0.1".  Your's might even be the same (worth trying, 127.0.0.1 is the same machine ASP.NET is running on) but you might have a specific server, e.g. "mail.myhost.com"
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BobHavertyComhAuthor Commented:
Hi Rouchie,

This makes sense to me and looks like it is going to work. I can't test it out yet because I am having problems with the display and behavior of the upload control itself where the button is showing up inside the upload text field instead of to the right of it and although it does allow me to browse, it doesn't show the filename and path in the text field portion after I select a file.

This is a different issue and therefore I am going to ask about this as a separate question and maybe you can pick up another quick 500 points. Then, after I can test your solution, I'll come back and give you the points, but I'm pretty sure what you posted is going to work just fine, and thanks for the language conversion info.
0
BobHavertyComhAuthor Commented:
Hi Rouchie,

Thanks for you other answer. The above works great except for one problem. The attachments shows up in the email but is is zero bytes. Any ideas? Apparently I do not need authentication for goddaddy.com as long as it is coming from their serving where it is hosted, and that all works fine. But somehow the filestream isn't generating any real file. I doubt it makes a difference, but I am sending it to my google mail account and I receive both emails if I put my email in the form. File name shows up, but size is 0

uploadForm.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;

public partial class uploadForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Net.Mail.SmtpClient mc = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net", 25);
        MailMessage mm = new MailMessage();
        mm.To.Add(new MailAddress(email.Text));
        mm.From = new MailAddress("no-reply@premaxmfg.com");
        mm.Subject = "Your file upload has been sent to PREMAX Mfg.";
        mm.Attachments.Add(new Attachment(fu.PostedFile.InputStream, fu.FileName));
        mm.Body = "Your file has been successfully sent to PREMAX Manufacturing. This is an auto generated confirmation email. Please do not respond. You have sent the following information:" + Environment.NewLine + "Name: " + name.Text + Environment.NewLine + "Company: " + company.Text + Environment.NewLine + "Email: " + email.Text + Environment.NewLine + "Phone: " + phone.Text + Environment.NewLine + "Uploaded File: See attached file";
        mc.Send(mm);
        mm.Dispose();

        MailMessage mm1 = new MailMessage();
        mm1.To.Add(new MailAddress("havertyrobert@gmail.com"));
        mm1.From = new MailAddress(email.Text);
        mm1.Subject = name.Text + " has sent you a file.";
        mm1.Attachments.Add(new Attachment(fu.PostedFile.InputStream, fu.FileName));
        mm1.Body = "Attached is a file sent to you by:" + Environment.NewLine + "Name: " + name.Text + Environment.NewLine + "Company: " + company.Text + Environment.NewLine + "Email: " + email.Text + Environment.NewLine + "Phone: " + phone.Text + Environment.NewLine + "Uploaded File: See attached file." + Environment.NewLine + "IMPORTANT!! Make sure you save this file first and scan it for viruses before opening it";
        mc.Send(mm1);
        mm1.Dispose();
        Response.Redirect("response.aspx");
    }
}

Open in new window


upload.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadForm.aspx.cs" Inherits="uploadForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link href="~/styles.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        body
        {
             margin:0 0 0 5px; 
             text-align:left;
             font-family:Arial;
             font-size:12px;
             color:#d6f8ef;
             text-shadow: #000 1px 1px;    
        }
        table input
        {
            border:1px solid #77a6c5;
            width:250px;
            height:18px;
            border-radius:5px;
            overflow:hidden;
            background:#d6f8ef;
            margin-bottom:7px;
        }
        table textarea
        {
            border:1px solid #77a6c5;
            width:350px;
            height:80px;
            border-radius:5px; 
            background:#d6f8ef;
            resize: none;
        }
        
        
        
        .submit
        {
            width:60px;
            height:20px;
            margin:10px 0 0 2px;
            font-weight:bold;
            color:#deeffa;
            border:0;
            border-radius:5px;
            overflow:hidden;
            background-color:#152f56;
            background-image:url("images/profileBg.png");
	        background-repeat:repeat-x;
        }
        
        .fustyle
        {
            background-color:#d6f8ef;
            color:#152f56;
            width:300px;
            height:25px;
            border-radius:5px;
            border:1px solid #77a6c5;
        }
    </style>
    <script language="javascript" type="text/javascript">
<!--

// -->
    </script>
</head>

<body>
    <form id="form1" runat="server">
        <table cellspacing="0" cellpadding="0">
            <tr>
                <td>
                <b>Name</b><br />
                <asp:TextBox ID="name" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                <b>Company</b><br />
                <asp:TextBox ID="company" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                <b>Email</b><br />
                    <asp:TextBox ID="email" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                <b>Phone</b><br />
                <asp:TextBox ID="phone" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                <b>Job Number or Description (if applicable)</b><br />
                <asp:TextBox ID="jobNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                <b>Select File to Upload</b><br />
                <asp:FileUpload ID="fu" cssclass="fustyle" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                <asp:Button ID="Button1" runat="server" CssClass="submit" onclick="Button1_Click" 
                Text="Send" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Open in new window


also available at www,curriersystems.com and click on the upload a file button at top right of the nav, or go direct at www.curriersystems.com/uploadForm.aspx
0
RouchieCommented:
This happens usually when you send a single attachment across multiple emails, or try referencing the uploaded file twice (e.g. save it first and also send it).  You can get over the problem by resetting the input stream's starting position before each reference to the uploaded file.

Change this:

mm.Attachments.Add(new Attachment(fu.PostedFile.InputStream, fu.FileName));

Open in new window


to this:

fu.PostedFile.InputStream.Position = 0;
mm.Attachments.Add(new Attachment(fu.PostedFile.InputStream, fu.FileName));

Open in new window


Full explanation here:
http://www.codepal.co.uk/show/Sending_Email_Attachments_From_a_FileUpload_Control_Sends_Empty_Files
0
BobHavertyComhAuthor Commented:
Spot on Rouchie. That was the problem. Thanks a bunch once again. I'll have to add this one to my knowledge base.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.