Friday, January 30, 2015

Sending Mail in .NET Using SmtpClient

The .NET SmtpClient class which is in the System.Net.Mail namespace enables the sending of mail through the ubiquitous Simple Mail Transfer Protocol (SMTP). To send a simple text-based mail, first instantiate an SmtpClient object, set its Host property to your SMTP server address, and finally call Send:
SmtpClient clientObj = new SmtpClient();
clientObj.Host = "mail.myisp.net";
clientObj.Send ("from@mydomain.com", "to@adomain.com", "subjecttext", "bodytext");
To control spam, most SMTP servers will only accept connections from the ISP’s subscribers, so you will need the SMTP address appropriate to the current connection for this to work.
Constructing a MailMessage object allows for more options such as adding attachments:
SmtpClient clientObj = new SmtpClient();
clientObj.Host = "mail.myisp.net";
MailMessage mmObj = new MailMessage();
mmObj.Sender = new MailAddress ("kay@domain.com", "Kay");
mmObj.From = new MailAddress ("kay@domain.com", "Kay");
mmObj.To.Add (new MailAddress ("bob@domain.com", "Bob"));
mmObj.CC.Add (new MailAddress ("dan@domain.com", "Dan"));
mmObj.Subject = "Hello!";
mmObj.Body = "Hi. Here's my photo!";
mmObj.IsBodyHtml = false;
mmObj.Priority = MailPriority.High;
Attachment a = new Attachment ("photoofme.jpg",
System.Net.Mime.MediaTypeNames.Image.Jpeg);
mmObj.Attachments.Add (a);
clientObj.Send (mmObj);
SmtpClient allows you to specify authentication credentials for any servers which require this. You can also specify EnableSsl if supported, and alter the TCP Port to a nondefault value. You can also change the DeliveryMethod property to enable you instruct the SmtpClient to use IIS for sending mail messages or to simply write each message to an .eml file in a directory you specify:
SmtpClient clientObj  = new SmtpClient();
clientObj.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
clientObj.PickupDirectoryLocation = @"c:mail";

No comments:

Post a Comment