Sending Emails from C#.NET

Sharing is Caring

Often, I work on software that needs to have the most minimal downtime possible. For example, I wrote a large chunk of server code that needs to handle CRM data for a small but completely distributed sales team. One of the methods, I use to try and reduce the downtime is to have the software email me whenever an exception is thrown or when some sort of event occurs.

Emails are incredibly easy to send from .NET especially your typical plaintext email. We will be making use of the System.Net.Mail namespace along with an smtp server you should already have setup or you could use a free one like Gmail.

A number of Canadian Internet Service Providers (ISPs) require you use their local SMTP Server (by blocking port 25), you should contact them if you think this will be an issue. Please note that some ISPs like Bell Sympatico do this to avoid being blacklisted for spam.

using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace BRCline1
{
public partial class frmEmailer : Form
{
private const string SMTPServer = “Your_SMTP_Address_Or_IP_Goes_Here”;
private const string FromAddress = “The_Sender_Address_Goes_here”;
private const string FromAddressPassword = “The_Sender_Password_Goes_here”;
private const int SMTPPort = 25; //Could also be another port

public Form1()
{
InitializeComponent();
}

private void btnSend_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(SMTPServer);

mail.From = new MailAddress(FromAddress);
mail.To.Add(“address@fakedomain.com”);
mail.Subject = “Your_Subject_Goes_Here”;

//Change this boolean to true, and you could send a simple html email
mail.IsBodyHtml = false;

mail.Body = “This is my first auto email”;

SmtpServer.Port = SMTPPort;
SmtpServer.Credentials = new System.Net.NetworkCredential(FromAddress, FromAddressPassword);

SmtpServer.Send(mail);
}
}
}

Please note that you should always have some sort of exception handling for any operation that depends on a network connection or another system from responding.

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring