How to send an email with attachment in asp.net 2.0
I have seen many posts over forums asking for how to send emails in asp.net.
In this blog post, I am going to post code snippet to send email in asp.net (with / without attachment).
MoreOver, for Complete FAQ for the System.Net.Mail namespace found in .NET
2.0 (Click here for System.Web.Mail). This is an excellent resource to understand total mail functionalities in asp.net.
Check out Below Code to send email in asp.net:
C#
using System.Net;
using System.Net.Mail;
-----------------------
public static bool SendMail(string strFrom, string strTo, string strSubject, string strMsg)
{
try
{
// Create the mail message
MailMessage objMailMsg = new MailMessage(strFrom, strTo);
objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = strSubject;
objMailMsg.Body = strMsg;
objMailMsg.Priority = MailPriority.High;
objMailMsg.IsBodyHtml = true;
//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objSMTPClient.Send(objMailMsg);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
VB:
Public Shared Function SendMail(ByVal strFrom As String, ByVal strTo As String, ByVal strSubject As String, ByVal strMsg As String) As Boolean
Try
' Create the mail message
Dim objMailMsg As MailMessage = New MailMessage(strFrom, strTo)
objMailMsg.BodyEncoding = Encoding.UTF8
objMailMsg.Subject = strSubject
objMailMsg.Body = strMsg
objMailMsg.Priority = MailPriority.High
objMailMsg.IsBodyHtml = True
'prepare to send mail via SMTP transport
Dim objSMTPClient As SmtpClient = New SmtpClient()
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
objSMTPClient.Send(objMailMsg)
Return True
Catch ex As Exception
Throw ex
End Try
End Function
Code to send mail with attechment.,
public static bool SendMail(string strFrom, string strTo, string strSubject, string strMsg)
{
try
{
// Create the mail message
MailMessage objMailMsg = new MailMessage(strFrom, strTo);
objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = strSubject;
objMailMsg.Body = strMsg;
Attachment at = new Attachment(Server.MapPath("~/Uploaded/txt.doc"));
objMailMsg.Attachments.Add(at);
objMailMsg.Priority = MailPriority.High;
objMailMsg.IsBodyHtml = true;
//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objSMTPClient.Send(objMailMsg);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
Referecned Thread link: How to send an email with attachment in asp.net 2.0 - ASP.NET Forums
hope this helps.