top of page

Emailing From a Console App



Hey kids! So we've determined that there are 400 ways to Sunday to try to email someone in an app or website. If you have access to an API for your company, you're in luck. If your company is in the dark ages and using old tech, this can be difficult.


This is the way I email in a console app that resides on a user's desktop. It may not be the most elegant, but it works .... and sometimes that's all that matters when your options are limited!!


You want to add using System.Net.Mail; to your class first. The MailMessage and SmtpClient objects are then available to you for use.




You will need to find what smtp protocol your company uses in order to secure the ability to mail via your app. The port should be the same as what's used below, but it depends on what ports are open, SSL, and firewalls used.


You will need to specify:

  • To email

  • CC email (optional)

  • Subject

  • From email

  • Message Body (optional)

  • Attachments (optional)

  • SSL

  • HTML

  • Port


static bool EmailData()
{

    MailMessage message = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("mailrelay.company.local");

    message.Subject = " Report -  " + DateTime.Today.Month + "/" + DateTime.Today.Day + "/" + DateTime.Today.Year;


    message.CC.Add("me@company.com");
#if DEBUG

#else
    message.To.Add("them@company.com");
#endif


    message.From = new MailAddress("itgroup@company.com");

    if (File.Exists(fullPath))
    {
        Console.WriteLine("File exists, add attachment");

        //check for valid file existing
        message.Attachments.Add(new Attachment(fullPath));
    }


    message.IsBodyHtml = true;
    message.Body = " report and Working Copy enclosed for " + todaydate;
    SmtpServer.Port = 587;
    SmtpServer.EnableSsl = false;

    try
    {
        SmtpServer.Send(message);
        Console.WriteLine("Email sent to: " + message.To.ToString());
        Console.WriteLine("Email cc'ed to: " + message.CC.ToString());

    }
    catch (Exception ex)
    {
        Console.WriteLine("Error sending email.  Error message: " + ex.Message);

    }

When sending an email this way, you will want to make sure you are adding error handling and logging because this is the only way anyone will know if an email send failed.


This may not be an option for everyone, based on how much a company email and security is locked down. This method is best to be used for internal email applications when possible, but can be used provided all the objects have been listed.


Enjoy sending emails!!!




27 views0 comments
bottom of page