C# Code to send a Mail

Mail Message
Mail Message@Image courtesy of jscreationzs/ FreeDigitalPhotos.net

C# Code to send a Mail

Welcome to CodeSpread!

While working in a project, we always neglect the importance of the code which we have written many times and now end up in copy pasting the code from old projects.

Lately, I saw a request in forum asking for code to send email in .Net. I was not able to answer his query properly as it was something that i wrote long back and because of copy pasting from old code, i had completely forgot how to do that. So Here i attempt to recollect my memories, I know its very simple and if some of you can help me add more value to this article,you are most welcome.

First thing first, we require a reference to the mail namespace in our cs file before we can start coding. we will include.

using System.Net.Mail;

This namespace will provide the necessary classes required to compose and send a mail. To compose a Mail, we have to create an instance of MaiMessage like

var mailMessage = new MailMessage();

There are members of this instance which are required to be assigned like ‘From’ Address, ‘To’ Address, subject, message body, any attachments. We have another class MailAddress which is used to create instance for ‘From’ Address and ‘To’ Address . I think if you see the code, then it would be much more clear.

mailMessage.From = new MailAddress("from");
mailMessage.To.Add(new MailAddress("to"));
mailMessage.Subject = "subject";
mailMessage.Body = "body";
if (!string.IsNullOrEmpty("fileName"))
mailMessage.Attachments.Add(new Attachment("fileName"));

Text written under quotes(“”) needs to be changes with your real values. Don’t miss that.

Now we have composed our message, only thing that remains now is to send it. Lets look, if we have some more class in our namespace to perform the operation. We certainly have a class SmtpClient to server our purpose.

var mailSmtpClient = new SmtpClient("SmtpHost", SmtpPort);
mailSmtpClient.Send(mailMessage);

We have created one instance of SmtpClient and passed the values of Smtphost which is the host-name of your mail server and the SmtpPort which has been configured to send a mail. Finally you just have to call their Send() method and pass your mail message. We have many overloads of all these methods available to facilitate the process but here, we have mentioned only the basic process. So, last step is to write all this code at one place.

var mailMessage = new MailMessage();
try
{
mailMessage.From = new MailAddress("from");
mailMessage.To.Add(new MailAddress("to"));
mailMessage.Subject = "subject";
mailMessage.Body = "body";
if (!string.IsNullOrEmpty("fileName"))
mailMessage.Attachments.Add(new Attachment("fileName"));

var mailSmtpClient = new SmtpClient("SmtpHost", SmtpPort);
mailSmtpClient.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}

That’s all from my side. Please provide your inputs.

Author: hershey

A passion for knowledge drives me to do programming, A passion for programming drives me to create something different, A passion for creation drives me to spread the knowledge.

Share This Post On

0 Comments

  1. nice superb explaination

    Post a Reply
  2. thanks for the tutorial
    I am having a problem.
    The feature “Create SQL server database” isn’t available , I can’t select it.
    Can you help, please ?

    Post a Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

More from CodeSpread:

  • C#: My experience with const keywordC#: My experience with const keywordThere are numerous post on internet about 'what is const keyword in .net' or 'what is the difference between const keyword and read only' and I must say many might have already mugged it up like me...
  • Nullable .Net typesNullable .Net typesWe declare .net types in our project daily but still we do not recollect default values for each .net type so we end up doing null check for each data type. Its a basic mistake of a developer but ....
  • Useful ‘ref’ and ‘out’ parametersUseful ‘ref’ and ‘out’ parameters It took me some time to realize the real potential of ref and out keywords, till the time I experience a condition which could only be simplified by implementing ref and out keyword. Lets st...
  • Asp.Net: Hidden Truth of CookiesAsp.Net: Hidden Truth of CookiesI know there are several articles on cookies as what are they? and how can they be created? but i always wanted to know more about them. My questions were where they are stored? how to track their ...
  • Asp.Net: More about CookiesAsp.Net: More about CookiesWe have seen, how our cookies looks in our last article Cookies Part 1. In this article, we will talk about their properties,limitations and technical part. Properties and Limitations Cook...
  • Concepts: S O L I DConcepts: S O L I DSOLID - Object oriented programming principles. May be its easy to forget these principles  but for creating a reusable code or maintainable code, people will always have to come back and check ...
  • SQL:My first SSIS PackageSQL:My first SSIS PackageI would like to share my experience about a situation, where I was given a task to export a file(say XML) from FTP location and get the data from this file populated into our database tables. Moreo...
  • Why Multiple Inheritance is discouraged?Why Multiple Inheritance is discouraged?Hi Guys, This is Sathish Again,Today we will discuss why most of the higher languages eliminates Multiple Inheritance? Most of you guys already know that multiple inheritance is not available for...