C#.NET Code to send mail
This article covres following things
- Send mail using C#.NET 2.0
- Send mail using .NET 1.1 or below version
- Send mail using ASP (CDONET)
- Domain Validation
- Account Validation
- Email Address Validation (client side and server side both)
1. Send mail using C#.NET 2.0
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 -->
<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.
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
- send email in HTML Format
- set email priority
- use the Carbon Copy(CC) and Blind Carbon Copy(BCC) functions as in any email client,
- 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;