Friday, February 01, 2008

C#.NET Code to send mail

C#.NET Code to send mail

This article covres following things

  1. Send mail using C#.NET 2.0
  2. Send mail using .NET 1.1 or below version
  3. Send mail using ASP (CDONET)
  4. Domain Validation
  5. Account Validation
  6. Email Address Validation (client side and server side both)

1. Send mail using C#.NET 2.0

In .NET 2.0 we can use new library system.Net.Mail, it provide configuration feature for mail setting. It is reliable and fast. Use following method to send mail.

Namespace

using System.Net.Mail;

C# Code

private bool SendMails(string fromEmailId)

{

try

{ string msgBody = string.Empty;

// Instantiate a new instance of MailMessage

MailMessage mMailMessage = new MailMessage();

// Set the sender address of the mail message

mMailMessage.From = new MailAddress(fromEmailId);

// Set the recepient address of the mail message

mMailMessage.To.Add(new MailAddress("ToEmailId"));

//Get subject from config file

mMailMessage.Subject = "MailSubject";

//encode subject optional

mMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

//Build Message body based on AccessPtypes

msgBody = BuildMessageBody(reqAccessPtypes);

// Set the body of the mail message

mMailMessage.Body = msgBody;

//encode body optional

mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

// Set the format of the mail message body as HTML

mMailMessage.IsBodyHtml = true;

// Set the priority of the mail message to normal

mMailMessage.Priority = MailPriority.Normal;

//Set attach files need to send optional

mMailMessage.Attachments.Add(new Attachment("C:\\test.pdf"));

// Instantiate a new instance of SmtpClient

SmtpClient mSmtpClient = new SmtpClient();

// Send the mail message

mSmtpClient.Send(mMailMessage);

}

catch (Exception ex)

{

return false;

}

return true;

}

Setting in web.config

<configuration>

<!-- Require settings to send email from this application -->

<system.net>

<mailSettings>

<smtp from="defaultEmail@yourdomain.com">

<network host="127.0.0.1" port="25" userName="yourUserName" password="yourPassword"/>

</smtp>

</mailSettings>

</system.net>

</configuration>

2. Send mail using .NET 1.1 or below version

Using .NET 1.1 or below version we use library System.Web.Mail, here also you can make mail setting configurable, write all setting in web.config file in AppSettings section. This library method now become obsolete in .NET 2.0 and above version. Use following method to send mail.

Namespace

using System.Web.Mail;

C# Code

private void SendMails(string fromEmailId)

{

try

{

// Instantiate a new instance of MailMessage

MailMessage msg = new MailMessage();

// Set the sender address of the mail message

msg.From = fromEmailId;

// Set the recepient address of the mail message

msg.To = "ToEmailId";

//Get subject from config file

msg.Subject = "MailSubject";

//Build Message body based on AccessPtypes

msg.Body = "Mail Body Text";

// Set the format of the mail message body as HTML

msg.BodyFormat = MailFormat.Html;

//set SMTPServer configuration IP address

SmtpMail.SmtpServer = "SMTPServer";

//send mail

SmtpMail.Send(msg);

}

catch (Exception ex)

{

throw ex;

}

}

3. Send mail using ASP (CDONET)

CDONTS (Collaborative Data Objects for Windows NT Server) provides you with objects and classes that enable you to send email from an ASP page. CDONTS only works on Windows NT/2000 Operating Systems. It supports following feature

  1. send email in HTML Format
  2. set email priority
  3. use the Carbon Copy(CC) and Blind Carbon Copy(BCC) functions as in any email client,
  4. attach files while sending email

You can use following code in ASP page to send mail

<%
Set Mail=Server.CreateObject("CDONTS.NewMail")
Mail.To="me@mydomain.com"
Mail.From="testing-my@SP-Script.com"
Mail.Subject="Just testing my script"
Mail.Body="This is test mail."
Mail.Send
Set Mail=nothing
%>

4. Domain Validation

After sending a mail we need to validate for domain as well as account whether "To" or "From" mail id and domain are valid or not, it can be validate from .NET code using System.Net.Sockets.

Note: Use of sockets requires a trust level above the default "Medium".

Namespace

using System.Net;

using System.Net.Sockets;

C# Code

string email = "recipient@domain.com";

string[] host = email.Split('@');

string hostName = host[1];

Socket socket;

try

{

IPHostEntry entry = Dns.GetHostEntry(hostName);

IPEndPoint endPoint = new IPEndPoint(entry.AddressList[0], 25);

socket = new Socket(endPoint.AddressFamily, SocketType.Stream,

ProtocolType.Tcp);

socket.Connect(endPoint);

}

catch (SocketException ex)

{

// Invalid email.

}

5. Account Validation

if (!CheckSmtpResponse(SmtpResponse.CONNECT_SUCCESS))

{ // invalid account }

//test TEST server

SendData(string.Format("TEST {0}\r\n", Dns.GetHostName()));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//test for sender domain on blacklist

SendData(string.Format("MAIL From: {0}\r\n", _SenderEmail));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//test send

SendData(string.Format("MAIL TO: {0}\r\n", email));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//account is valid!

//utility funtions:

void SendData(string message)

{

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(message);

socket.Send(bytes, 0, bytes.Length, SocketFlags.None);

}

enum SmtpResponse : int {

CONNECT_SUCCESS = 220,

GENERIC_SUCCESS = 250,

DATA_SUCCESS = 354,

QUIT_SUCCESS = 221

}

bool CheckSmtpResponse(SmtpResponse code) {

string responseString;

int responseCode;

byte[] bytes = new byte[1024];

while (socket.Available == 0) {

System.Threading.Thread.Sleep(100);

}

socket.Receive(bytes, socket.Available, SocketFlags.None);

responseString = System.Text.Encoding.ASCII.GetString(bytes);

responseCode = Convert.ToInt32(responseString.Substring(0, 3));

return responseCode.Equals(Convert.ToInt32(code));

}

6. Email Address Validation

Namespace

using System.Text.RegularExpressions;

C# Code

private bool EmailAddressIsValid(string email)

{

string regExPattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +

@"\.[0-9]{1,3}\.[0-9]{1,3}\.)(([a-zA-Z0-9\-]+\" +

@".)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$";

Regex regEx = new Regex(regExPattern);

return regEx.IsMatch(email);

}

JavaScript Code

For the client side email validation you can use following javascript function

//Validates the email address given.

var strEmailValidationRegExp = /^([a-zA-Z0-9_\-\.]+)@((\[?[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]?)(([a-zA-Z0-9\-]+\.)+)([a-zA-Z]{2,4}))$/;

function ValidateEmailAddress()

{

var strEmailToValidate = document.getElementById('txtEmailAddress').value;

//Valid characters allowed in the id.

var regExp = new String();

regExp = strEmailValidationRegExp;

// chk for mandatory field

if(strEmailToValidate.length == 0)

{

alert("Please enter the eMail Address.");

document.getElementById("txtEmailAddress").focus();

retVal = false;

} // chk for valid email address

else if(!regExp.test(strEmailToValidate))

{

alert("Please enter a valid eMail Address.");

document.getElementById("txtEmailAddress").focus();

retVal = false;

}

return retVal;

}

15 comments:

PRATS said...

Hi Ritesh,
I get an error using the 1st one as Failure to send the email. Can u please let me know whr i can go wrong
I have included the code as per what u ve mentioned and also in that of the web config

Thanks.

Anonymous said...

[url=http://firgonbares.net/][img]http://firgonbares.net/img-add/euro2.jpg[/img][/url]
[b]academic software pricing, [url=http://firgonbares.net/]office 2007 enterprise serial[/url]
[url=http://firgonbares.net/][/url] where can i get a cracked copy of photoshop cs4 for mac buy adobe software
student discount software uk [url=http://firgonbares.net/]Advanced Mac[/url] buy downloadable software
[url=http://firgonbares.net/]discount software australia[/url] and software stores
[url=http://firgonbares.net/]acdsee s-sw58 software[/url] shop pro software
software from microsoft [url=http://firgonbares.net/]make to order software[/b]

Anonymous said...

[url=http://sunkomutors.net/][img]http://sunkomutors.net/img-add/euro2.jpg[/img][/url]
[b]nero 9 patch, [url=http://sunkomutors.net/]academic planner software[/url]
[url=http://sunkomutors.net/][/url] my office software adobe photoshop cs3 manual
acdsee 10 photo manager [url=http://sunkomutors.net/]purchase of softwares[/url] buy igo software
[url=http://sunkomutors.net/]qxp quarkxpress free download reader[/url] adobe premium creative suite 4 manual
[url=http://sunkomutors.net/]ict software shop imperial[/url] photo order software
where to buy old software [url=http://sunkomutors.net/]photo software downloads[/b]

Anonymous said...

Hi !.
You re, I guess , probably curious to know how one can collect a huge starting capital .
There is no need to invest much at first. You may commense earning with as small sum of money as 20-100 dollars.

AimTrust is what you need
The company represents an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with affiliates around the world.
Do you want to become an affluent person?
That`s your choice That`s what you desire!

I feel good, I began to take up income with the help of this company,
and I invite you to do the same. If it gets down to choose a correct companion who uses your savings in a right way - that`s it!.
I make 2G daily, and my first investment was 500 dollars only!
It`s easy to start , just click this link http://jocizaduw.kogaryu.com/lijuhymi.html
and go! Let`s take our chance together to feel the smell of real money

Anonymous said...

Hi !.
You may , perhaps very interested to know how one can manage to receive high yields .
There is no need to invest much at first. You may commense to receive yields with as small sum of money as 20-100 dollars.

AimTrust is what you need
The firm incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with offices everywhere: In USA, Canada, Cyprus.
Do you want to become an affluent person?
That`s your chance That`s what you wish in the long run!

I feel good, I started to get real money with the help of this company,
and I invite you to do the same. It`s all about how to select a proper partner utilizes your money in a right way - that`s AimTrust!.
I take now up to 2G every day, and what I started with was a funny sum of 500 bucks!
It`s easy to join , just click this link http://vifoqeduq.lookseekpages.com/xujyrybe.html
and go! Let`s take our chance together to become rich

Anonymous said...

[url=http://vonmertoes.net/][img]http://bariossetos.net/img-add/euro2.jpg[/img][/url]
[b]buy sat nav software, [url=http://hopresovees.net/]cheapest software[/url]
[url=http://hopresovees.net/][/url] purchase linux software software prices uk
best web store software [url=http://vonmertoes.net/]i buy cheap software[/url] ut software store
[url=http://vonmertoes.net/]buy erp software[/url] office 2003 download
[url=http://vonmertoes.net/]Mac Poser 7 Cyberlink[/url] discount software for non
software graphics macromedia fireworks 8 [url=http://vonmertoes.net/]free adobe photoshop cs4 user guide download[/b]

Anonymous said...

Good day, sun shines!
There have were times of hardship when I felt unhappy missing knowledge about opportunities of getting high yields on investments. I was a dump and downright pessimistic person.
I have never imagined that there weren't any need in large initial investment.
Now, I'm happy and lucky , I begin to get real income.
It gets down to choose a proper companion who uses your funds in a right way - that is incorporate it in real deals, and shares the profit with me.

You can get interested, if there are such firms? I'm obliged to tell the truth, YES, there are. Please be informed of one of them:
http://theinvestblog.com [url=http://theinvestblog.com]Online Investment Blog[/url]

Anonymous said...

Good day, sun shines!
There have were times of troubles when I felt unhappy missing knowledge about opportunities of getting high yields on investments. I was a dump and downright stupid person.
I have never thought that there weren't any need in big initial investment.
Now, I feel good, I started to get real income.
It gets down to select a correct partner who utilizes your funds in a right way - that is incorporate it in real business, parts and divides the income with me.

You can get interested, if there are such firms? I have to answer the truth, YES, there are. Please get to know about one of them:
http://theinvestblog.com [url=http://theinvestblog.com]Online Investment Blog[/url]

Anonymous said...

Do You interesting of [b]Generic Viagra in Canada[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Generic Viagra in US and Canada[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/buy%20viagra/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also [url=http://twitter.com/tlkzfdn]Cheap Viagra 25mg[/url] you can find on our sites.
Generic [url=http://wumenalu.freehostia.com]Best Price 100mg Viagra[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]about viagra pill
cheapest price viagra deliverd uk
viagra for paxil side effects
Viagra Alternative
does viagra help women
viagra and jumex combination
Viagra Cocktail Recipe
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

Anonymous said...

Do You interesting of [b]Female use of Viagra[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Female use of Viagra[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/buy%20viagra/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also [url=http://twitter.com/jetlyca]q Buy Viagra Online[/url] you can find on our sites.
Generic [url=http://viagra.olistupa.ru]Viagra Super Active[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]Reliable Viagra
taking too much viagra
free trail viagra
Viagra Czas Dzialania
Viagra Diabetic Retinopathy
viagra tv ad
patrick adler kamagra generic viagra
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

Anonymous said...

Do You interesting of [b]Female use of Viagra[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Female use of Viagra[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/viagra%2C%20tramadol%2C%20zithromax%2C%20carisoprodol%2C%20buy%20cialis/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/viagra%2C%20tramadol%2C%20zithromax%2C%20carisoprodol%2C%20buy%20cialis/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also you can find on our sites.
Generic [url=http://viagra.wilantion.ru]Viagra 100mg pills[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]medical side affects of viagra
Viagra Cheap Buy
Viagra Voor Vrouwen
Viagra Uk Nhs
Viagra Uk Delivery
Viagra In Deutschland Bestellen
wild horses viva viagra
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

venkata said...

le erri pooka rntike le neki blog

venkata said...

sherwa taugle erripookoda

venkata said...

neekendukura blog uselss fellow of india first get uo and wash ur kdney and ur hand sdirty boy u dont no wwashing ur kidney and ur hands useless fellow

sudhee said...

le dodiki kurchoni gudda kadukovadam raanodu kooda blog lo petteda