Using .NET to Send Email

E-mail is one of the most common and reliable methods of communication for both personal and business purposes. It also plays an important role in each and every Web site. This role will be in the type of automated e-mails from the server after posting information from a form. You may have noticed these types of e-mails while registering on a site. As soon as you post the form, the server will send an e-mail asking you to confirm either your registration or with the information you entered. If you have to confirm the registration, the server will send you a long URL that you have to click to proceed further with the registration process. A classic example of this functionality is ASP.NET forums. As soon as you register, you will be e-mailed a random password. You will also get e-mails after your post has been accepted by a moderator or if somebody replies to your post. If you are wondering that this is a server magic—it is not. The whole process is made possible with the help of server-side programming languages such as ASP and ASP.NET.

Classic ASP provided a component named CDONTS that a developer should use intelligently to provide e-mail functionality on his or her applications. But this component lacked major functionalities. You can easily send an e-mail, but the process is very difficult for sending e-mails with attachments, HTML versions, and so forth. Almost all server-side languages provide some sort of solution for achieving these tasks. But, ASP.NET simplified the work of developers with the introduction of a special .NET namespace called System.Web.Mail. Moreover, it is very tedious to upload a file to a server with ASP. You have to depend upon third-party components. ASP.NET ships with a cute built-in uploading capability with which your users can easily upload their files. They can also send the file as an attachment along with their e-mails. In this article, you will learn how to send different types of e-mails with ASP.NET.


The .NET Framework supplies a SMTP class that enables you to send a simple e-mail message. If you have to send an e-mail with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can insert attachments, set priorities, and much more, very easily. You can also send HTML e-mail using this class.


Sending a Simple E-Mail Message
To send an e-mail with a simple text message, you have to use the Send() method of SMTP class. The syntax of the Send() method is shown in Listing 1.1 and an example is shown in Listing 1.2:


Listing 1.1
SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY");


Listing 1.2
SmtpMail.Send("mymail@domain.com","youremail@yourdomain.com","Thank You",
"Mail to Send");

Listing 1.3

 
MailMessage objEmail = new MailMessage();
objEmail.To = txtTo.Text;
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCc.Text;
objEmail.Subject = "Test Email";
objEmail.Body = txtName.Text + ", " +txtComments.Text;
objEmail.Priority = MailPriority.High;
objEmail.BodyFormat = MailFormat.Html;
// Make sure you have appropriate replying permissions from your local system
//SmtpMail.SmtpServer = "localhost";
try{
    SmtpMail.Send(objEmail);
   }
catch (Exception exc){
    //Print error
}  


Sending E-Mail Messages Using SMTP authontication

Listing 1.4

 using System.Net;
 using System.Net.Mail;

 MailMessage mailMessage = new MailMessage();
 mailMessage.To.Add(new MailAddress(to, toname));
 mailMessage.From = new MailAddress(from, fromname);
 mailMessage.Sender = new MailAddress(sender, sendername);
 mailMessage.ReplyTo = new MailAddress(replyto);
 mailMessage.Subject = subject;
 mailMessage.Body = body;
 mailMessage.IsBodyHtml = true;
 if (files != null)
   if (files.Length > 0)
     mailMessage.Attachments.Add(new Attachment(files[0]));
 // Create the credentials to login to the gmail account associated with my custom domain 
 NetworkCredential cred = new NetworkCredential(sender, pwd);
 //This is for Gmail Account, you can use your own domain here 
 SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 465);
 mailClient.EnableSsl = true;
 mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
 mailClient.UseDefaultCredentials = false;
 mailClient.Timeout = 20000;
 mailClient.Credentials = cred;
 mailClient.Send(mailMessage);  

Listing 1.5
 
using System.Web.Mail;


MailMessage myMail = new MailMessage();
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
/*
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//Use 0 for anonymous        
*/
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword);
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
    System.Web.Mail.MailAttachment MyAttachment = new System.Web.Mail.MailAttachment(pAttachmentPath);
    myMail.Attachments.Add(MyAttachment);
    myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);

Source: http://msdn.microsoft.com/en-us/library/system.web.mail.mailmessage(VS.71).aspx

Note: If you are using your local system (Server = localhost) instead of a real live server, you should properly enable relying on the Internet Information Server (IIS).

Table 1: MailMessage class properties


PropertyDescription
AttachmentsUsed for sending e-mails with attachments
FromSender's e-mail address
ToRecipient's e-mail address
CcRecipient's e-mail address (Carbon Copy)
BccRecipient's e-mail address (Blind Carbon Copy)
BodyText of the e-mail message
BodyFormatSpecifies the format of an e-mail message (Possible Values: Text, Html)
PrioritySpecifies the priority of an e-mail message (Possible Values: High, Low, and Normal)
SubjectDenotes the subject of an e-mail message
HeadersDenotes a collection of acceptable headers (Example: Reply-To)
BodyEncodingSpecifies the method of encoding an e-mail message (Possible Values: Base64 and UUEncode)

No comments: