SiteMap  | About    

ASP.NET Email Attachment

The System.Net classes uses to communicate with other applications by using the HTTP, TCP, UDP, Socket etc. In the previous chapter we saw how to SMTP email from ASP.NET describes how to send an email with text body . Here in this chapter we are trying to send and email with attachment file.


System.Net.Mail.Attachment class is used with the MailMessage class for sending an email with attachment. Attachment content can be a String, Stream, or file name. You can specify the content in an attachment by using any of the Attachment constructors.
  Dim attachment As System.Net.Mail.Attachment
  attachment = New System.Net.Mail.Attachment(attachmentFile)


  System.Net.Mail.Attachment attachment;
  attachment = new System.Net.Mail.Attachment(attachmentFile);


The following ASP.NET program shows how to send an email with an attachment from a Gmail address . The Gmail SMTP server name is and the port using send mail is 587 . Here we are using NetworkCredential for password based authentication.
  SmtpServer.Port = 587
  SmtpServer.Credentials = New System.Net.NetworkCredential("gamil-username", "gmail-passowrd")

SmtpServer.EnableSsl = True

  SmtpClient SmtpServer = new SmtpClient("");
  SmtpServer.Port = 587;

SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");

The above code you have to replace username and password with you gmail user name and password. Also you have to provide the from address as your gmail address.

  mail.From = New MailAddress("")


  mail.From = new MailAddress("");

There is file upload control using in this program for uploading the file from your system to web server.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head id="Head1" runat="server">
<title>Untitled Page</title>
	<form id="form1" runat="server">
		<asp:Label ID="Label2" runat="server" Text="To : "></asp:Label>
		<asp:TextBox ID="to_txt" runat="server" Width="200px"></asp:TextBox>
		<br /><br />
		<asp:Label ID="Label3" runat="server" Text="Subject :"></asp:Label>
		<asp:TextBox ID="subject_txt" runat="server" Width="200px"></asp:TextBox>
		<br />
		<br />
		<asp:Label ID="Label4" runat="server" Text="Message :"></asp:Label>
		<br />
		<asp:TextBox ID="message_txt" runat="server" Height="117px"
		TextMode="MultiLine" Width="339px"></asp:TextBox>
		<br />
		<br />
		<asp:Label ID="Label5" runat="server" Text="Select Upload File"></asp:Label>
		<asp:FileUpload ID="FileUpload1" runat="server" />
		<br />
		<br />
		<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send Mail"
		Width="123px" />
		<br />
		<br />
		<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Click the following links to see full source code

C# Source Code
VB.NET Source Code
default.aspx.vb (C) 2018    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.