A simple Mail Send function from ASP.Net
Many times your ASP.Net website contains a Contact form or an E-mail functionality then you need to write a code to send E-mail. Following code will help you in this.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Windows.Forms;
public class MailSend
{
string ServerName = “”;
int PortNumber = -1;
string MailFrom = “”;
string MailTo = “”;
string SubjectTitle = “”;
string MessageBody = “”;
// string AttachmentPath = “”;
string PasswordMailFrom = “”;
string Userpassword=”";
string userSubscribername=”";
int userProfileId = 0;
public MailSend(string mailToID,int profileId, string username,string password)
{
ServerName = “smtp.gmail.com”;
PortNumber = 587;
MailFrom = “xyz@gmail.com”;
PasswordMailFrom = “******”;
SubjectTitle = “Your Mail Subject”;
MessageBody = “Your Message Body”;
// AttachmentPath = “C:\Document and settings\Max\Desktop”;
MailTo=mailToID;
userSubscribername=username;
Userpassword=password;
}
/// <summary>
/// method of Sending the mail
/// </summary>
/// <returns>Void</returns>
public void sendMail()
{
MessageBody = getMessageBody();
MailMessage mail = new MailMessage(MailFrom, MailTo, SubjectTitle, MessageBody);
mail.IsBodyHtml = true;
//mail.CC.Add(“abc@gmail.com”);
SmtpClient smtp = new SmtpClient(ServerName, PortNumber);
//mail.Attachments.Add(new Attachment(AttachmentPath));
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(MailFrom, PasswordMailFrom);
smtp.EnableSsl = true;
smtp.Timeout = 300000;
try
{
smtp.Send(mail);
//MessageBox.Show(“Mail Sent successfully…”);
//Console.WriteLine(“Mail Sent successfully…”);
}
catch (Exception ex)
{
//Console.Write(“Send failed” + ex.Message);
//MessageBox.Show(“Send failed” + ex.Message);
}
}
/// <summary>
/// Method of generationg mail body
/// </summary>
/// <returns>string IMEI</returns>
public string getMessageBody()
{
string messageBodyString = “”;
messageBodyString+=”<html> <Title> Hello All </title> <body> <table border=’0′ cellpadding=’0′ cellspacing=’0′ width=’100%’>”;
messageBodyString+=”<tr><td width=’3%’> <img src=’file:///C:/projects/my_img.gif’ width=’34′ height=’30′></td>”;
messageBodyString += “<td background=’file:///C:/projects/my_img1.gif’>
return messageBodyString;
}
}
Hi,
I needed to drop you a quick note to impart my thanks. I’ve been watching your blog for a month or so and have picked up a heap of sound information as well as enjoyed the way you’ve structured your site. I am setting about to run my own blog however I think its too general and I would like to focus more on smaller topics.