Home > Code > ASP.NET > Sending Mails with Attachements using Asp.Net

Sending Mails with Attachements using Asp.Net

by Narain_Siddharth   on Nov 13, 2010   Category: ASP.NET   |  Views: 362    |  Points: 25   |  Silver 




Below is the sample code for sending emails with attachments.

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.Text;

namespace TestWeb.aspdotnet
{
public partial class mail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strSMTP = "SMTP Server Name";
int strPort = 25; //Default 25
MailMessage msg = new MailMessage("from Mail-ID", "To Mail-ID");
msg.CC.Add("CC mail-ID");// If necessary
msg.Body = "Test Mail";
msg.Subject = "Test Subject";
msg.BodyEncoding = Encoding.ASCII;
msg.IsBodyHtml = true;
msg.SubjectEncoding = Encoding.UTF8;
//Attachment Part
Attachment attach1 = new Attachment(@"Path");//Attachment Path
msg.Attachments.Add(attach1);
SmtpClient smtp = new SmtpClient(strSMTP);
System.Net.NetworkCredential nc = new System.Net.NetworkCredential("UserName", "Pwd", "Domain");
smtp.Credentials = (System.Net.ICredentialsByHost)nc.GetCredential(strSMTP, strPort, "Basic");
try
{
smtp.Send(msg);
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
Response.End();
}
}

}
}



If you find this above code useful, please leave your comments.



Like this code? Bookmark and Share:

  User Responses | Post Code
Comment posted by Spidy on 10/03/2011 | Points : 5
very useful code.
Can you post code for sending emails with GMAIL account using asp.netm if possible.

Thanks
Spidy.
  Recent Posts
* Setting focus to textbox control using JavaScript (308) by Narain_Siddharth on Nov 13 2010 11:25AM
* Sending Mails with Attachements using Asp.Net (362) by Narain_Siddharth on Nov 13 2010 11:48AM
* Disable the Submit button when insert or update a record using JavaScript (277) by Narain_Siddharth on Nov 13 2010 12:31PM
* String comparisons using C#.NET string.compareTo (289) by Thamilselvanj on Nov 14 2010 11:16AM
* String.Split using C# (287) by Thamilselvanj on Nov 14 2010 11:23AM
  Submit feedback about this code snippet
Please sign in to post feedback