CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Send Email with Attachment directly from FileUpload control in ASP.Net

By Bala Murugan
Posted On Dec 08, 2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 4
Category: ASP.Net
Print this article.

Send Email with Attachment directly from FileUpload control in ASP.Net

Sending email is one of the most repeated tasks we do in any asp.net website we develop. At times, we may need to allow users to attach some files when sending the email in our applications. Normally, we will use the FileUpload control available in the asp.net control set to upload or attach files to the server. Moving forward, this little article will help us to attach the files directly from the FileUpload control without saving to a temporary location and send it as an attachment in the email.

 

Steps

1.      In your Visual Studio 2008, click File > New > WebSite. Select "Asp.Net WebSite" and name it as per your need. In the Language DropDownlist, select C#.

2.      Now, design your email sending form in Default.aspx with a FileUpload control for file attachment.

Refer the below code,

<div>

        To <b>Admin</b> <br>

        From <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>

        <br />

        Subject <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>

        <br />

        Message <asp:TextBox ID="txtBody" runat="server" Height="70px" TextMode="MultiLine"

            Width="190px"></asp:TextBox>  <br />

        Attachment <asp:FileUpload ID="fuAttachment" runat="server" />

        <br />

        <asp:Button ID="btnSend" runat="server" Text="Send" onclick="btnSend_Click" />

        <br />   

    </div>

 

The above code will help you to compose the email content with attachment.

txtFrom – From Email ID.

txtSubject – Subject of your email.

fuAttachment – file Upload control to attach files.

btnSend – On clicking this button, you will be able to send the email.

 

3.      In the Send button click, we can pick up the attachment and the email content dynamically to send as an email.

Refer the below code,

protected void btnSend_Click(object sender, EventArgs e)

    {

        MailMessage mail = new MailMessage();

        try

        {

            mail.To.Add("admin@yourdomain.com");

            mail.From = new MailAddress(txtFrom.Text);

            mail.Subject = txtSubject.Text;

            string Body = txtBody.Text;

            mail.Body = Body;

            mail.Attachments.Add(new Attachment(fuAttachment.FileContent, System.IO.Path.GetFileName(fuAttachment.FileName)));

            SmtpClient smtp = new SmtpClient();

            smtp.Host = ConfigurationManager.AppSettings["SMTP"];

            smtp.Send(mail);

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

        finally

        {

            mail.Dispose();

        }

    }

 

The above code will pick your attachment directly from the FileUpload control without saving it to any temporary location. Thanks to the Attachment class which made this to happen with very less effort.

4.      Now, configure your SMTP server in the AppSettings of your Web.config file for sending the email.




Refer below,

<appSettings>

      <add key="SMTP" value="localhost"/>    

    </appSettings>

 

In my case, I have used localhost; it may be a different server in your case. Without this configuration, you may not be able to send the email in your application.

 

5.      That’s it! Execute the application and see it in action.

 

Conclusion

The introduction Attachment class in .Netframework 2.0 made sending attachment more secure and flexible by providing a way to attach the file directly without saving it to a temporary location. Since, it is an example; I have not done any validation on the user input (email id, content and files). You have to make sure there is a proper validation is in place in order to stay secured! You can read more on sending emails in asp.net from here.

 

Happy Mailing!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
sdfsdfsdf
fsdgfgdf
ff
ffff
abc
hi
send mail with attachment
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<p>
Please Fill the Following to Send Mail.</p>
<p>
Applied for:
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
ControlToValidate="YourName" ValidationGroup="save" /><br />
<asp:TextBox ID="txtpost" runat="server" Width="242px" Height="22px" /><br /><br />
Experience:
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="*"
ControlToValidate="YourName" ValidationGroup="save" />
<asp:DropDownList ID="ddlexp" runat="server">
<asp:ListItem>0-1 year</asp:ListItem>
<asp:ListItem>1-2 year</asp:ListItem>
<asp:ListItem>2-3 year</asp:ListItem>
<asp:ListItem>3 or above year</asp:ListItem>
</asp:DropDownList>
<br />
<br />
Your name:
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ErrorMessage="*"
ControlToValidate="YourName" ValidationGroup="save" /><br />
<asp:TextBox ID="YourName" runat="server" Width="250px" Height="22px" /><br /><br />
Your email address:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
ControlToValidate="YourEmail" ValidationGroup="save" /><br />
<asp:TextBox ID="YourEmail" runat="server" Width="250px" Height="22px" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator23"
SetFocusOnError="true" Text="Example: username@gmail.com" ControlToValidate="YourEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
ValidationGroup="save" /><br /><br />

Your Contact No.:
<br />
<asp:TextBox ID="txtno" runat="server" Width="184px" Height="22px"
style="margin-bottom: 0px" /><br /> <br /><br />
Upload Your CV:
<asp:FileUpload id="fileUpload1" runat="server" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />

</p>
<p>
<br />
<br />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Send"
OnClick="btnSubmit_Click" ValidationGroup="save"
style="height: 26px" />
</p>

<p>

</p>
</div>
</form>
</body>
</html>


protected void btnSubmit_Click(object sender, EventArgs e)
{

MailMessage mail = new MailMessage();
try
{
//enter receipient id.
mail.To.Add("mailid@gmail.com");//your mail id
mail.From = new MailAddress(YourEmail.Text);
mail.Subject = YourName.Text;

string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Applied For: " + txtpost.Text + "\n";
body += "Contact No.:" + txtno.Text + "\n";
body += "Experience:" + ddlexp.SelectedItem.Text + "\n";
mail.Body = body;
mail.Attachments.Add(new Attachment(fileUpload1.FileContent, System.IO.Path.GetFileName(fileUpload1.FileName)));
SmtpClient smtp = new SmtpClient();


smtp.Port = 587; // Gmail works on this port
smtp.Host = "smtp.gmail.com";
System.Net.NetworkCredential nc = new System.Net.NetworkCredential("mailid@gmail.com", "enter your password");// is u are using Gmail
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = nc;


smtp.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mail.Dispose();
}
txtno.Text = "";
txtpost.Text = "";
ddlexp.SelectedIndex = 0;
YourEmail.Text = "";
YourName.Text = "";



}