Wednesday, September 7, 2011

C# code for send Email

The below sample code showing how to send an email in asp.net


using System.Net.Mail;

string strFromAdd = "sample@gmail.com";
string strFromAddPass = "123456789";
string strSubject = "Subject Text";
string mailstring ="Mail Content";
string strAttachmentPath = Server.MapPath("..\\file\\sample.pdf");
MailMessage mail = new MailMessage();
mail.To.Add(strToAdd);
mail.From = new MailAddress(strFromAdd);
mail.Subject = strSubject;
mail.BodyEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(mailstring, @"%&$^/<(.|\n)*?>", string.Empty), null, "text/plain");
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailstring, null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
mail.Attachments.Add(new Attachment(strAttachmentPath));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Port = 587;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(strFromAdd, strFromAddPass);
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);

No comments:

Post a Comment