Managing the sending and receiving of messages are recurring needs in many applications. Because you can be faced with it one day, it's better to get to work by exploring the .Net framework that will allow you to easily implement this feature. The purpose of this article is to present as much as possible, the many features offered by the .Net framework
The e-mail can be used in various ways: notification, report or sending "personal" mail.
The Microsoft team has recognized this need and has developed two new namespaces that facilitate the sending of email.
Both namespaces are System.Net.Mail and System.Net.Mime which respectively, create a Mail object (MailMessage) and manage MIME headers of messages.
We will create the object representing our mail :
This class contains a significant number of properties allowing to customize the email as you would do with your email client. Start by defining the author of the email. This is done using the MailAddress class.
myMail.From = new MailAddress ("firstname.lastname@example.org");
The second thing is to define the recipient (s).
/ / Add the two main recipients
myMail.To.Add (new MailAddress ("email@example.com"));
myMail.To.Add (new MailAddress ("firstname.lastname@example.org "));
/ / Add a CC recipient
myMail.Cc.Add (new MailAddress ("email@example.com"));
/ / Add a recipient CCI
myMail.CCi.Add (new MailAddress ("firstname.lastname@example.org"));
As you can see, it is very easy to specify the recipients of the email and especially to define several recipients while specifying at which group of reception they belong .
Now specify the subject (title) of the email and its contents
myMail.Subject = "Test Mail";
myMail.Body = "Hello people";
Your email is ready to be sent.Let's create an object and configure the SMTPClient:
/ / Create SMTPClient
SmtpClient client = new SmtpClient ();
/ / Set the SMTP server
client.Host = "smtp.payong.com";
/ / Set the login and pwd if SMTP secure
client.Credentials = new NetworkCredential ("adrien", "password");
To send the mail we can write:
It is possible to include attachments to your emails. Each attachment is represented by an object Attachment
It is possible to include attachments to your emails. you will find that their use is just as simple.
Each attachment is represented by an object Attachment
/ / Create the attachment
attachment piece = new Attachment (@ "c :/ file ") / / path of the attachment
/ / Add the attachment to the email
/ / Delete the attachment