Send Mail in C#

For building distributed applications and SPY tools it’s very necessary that the application can send information to remote server, without getting blocked by the firewalls. In visual studio there are built-in frameworks by which one can send mail by using it’s own resources i.e. without using Operating system’s tools.

Image source from internet

The following shows the code in C#. The code is tested and will work in .NET framework 2.0 and above

using System;
using System.Collections.Generic;
using System.Text;

namespace sendmail
{
class Program
{
static void Main(string[] args)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
/*-----------------------------
Provide your mail server user-id and password
--------------------------------- */
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("[email protected]", "demopassword");

/*---------------------------------------------
Provide Receiver Mail addresses

You can set as many receivers by repeating the function
----------------------------------------------*/

mail.To.Add("[email protected]");
mail.Subject = "Demo Subject " ; /* Mail subject */

mail.From = new System.Net.Mail.MailAddress("[email protected]"); // Provide your full mail-id
mail.IsBodyHtml = true;


/*--------------------

Provide mail body or actual message

-------------------------*/
mail.Body = "Mail from C#";



System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com"); // Provide SMTP server

smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true; // false to disable SSL
smtp.Credentials = cred;
smtp.Port = 587; // Port number for SMTP
try
{

smtp.Send(mail); // send mail

}
catch (Exception e)
{

/*-----------------------------
You can code your own customized error message in this catch block
------------------------------*/
Console.WriteLine("Can't sent mail :: "+ e);
}

}
}

To add attachments  you can use the following function..
/*-------------------------------------------
You can set as many attachments by
repeating the function and providing the path
---------------------------------------------*/
mail.Attachments.Add(new Attachment("c:\demofile.txt"));


Share Button

Leave a Reply

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