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.
|