Blog

Filter posts by the Tags of Blog section!

Email Sender Helper using C# and Microsoft .Net Mail Friday, 22 January 2016

using System;

using System.Net;

using System.Net.Mail;



public static class EmailHelper

{

    public static async void SendMail(MailParams mail)

    {

        try

        {

            if (IsValidEmails(mail.Settings.SenderAddress, mail.To.Address) == false)

                throw new Exception($"{mail.Settings.SenderAddress} or {mail.To.Address} are not true");



            var smtpClient = new SmtpClient

            {

                Host = mail.Settings.Host,

                Port = 587,

                EnableSsl = true,

                Credentials = new NetworkCredential(mail.Settings.SenderAddress, mail.Settings.SenderPassword)

            };



            using (var message = new MailMessage(mail.Settings.SenderAddress, mail.To.Address))

            {                    

                message.IsBodyHtml = true;

                message.Subject = mail.Subject;

                message.Body = mail.Body;



                await smtpClient.SendMailAsync(message);

            }

        }

        catch (Exception exception)

        {

            throw exception;

        }

    }



    private static bool IsValidEmails(params string[] emails)

    {

        try

        {

            foreach (var item in emails)

            {

                var addr = new MailAddress(item);

                if (addr.Address != item)

                    return false;

            }

            return true;

        }

        catch

        {

            return false;

        }

    }

}



public class MailParams

{

    public MailParams(MailSetting mailSetting)

    {

        Settings = mailSetting;

    }



    public MailSetting Settings { get; set; }



    public Mail To { get; set; }



    public string Body { get; private set; }

    public string Subject { get; private set; }



    public void SetBody(string body)

    {

        Body = body;

    }

    public void SetSubject(string subject)

    {

        Subject = subject;

    }

}



public class MailSetting

{

    public string Host { get; set; }

    public int Port { get; set; }

    public bool EnableSsl { get; set; }

    public int Timeout { get; set; }

    public bool UseDefaultCredentials { get; set; }

    public string SenderAddress { get; set; }

    public string SenderPassword { get; set; }

    public string DisplayName { get; set; }

}



 public class Mail

{

    public Mail(string address, string displayName = "", string password = "")

    {

        Address = address;

        DisplayName = displayName;

        Password = password;

    }



    public string Address { get; private set; }

    public string Password { get; private set; }

    public string DisplayName { get; private set; }

}

 

No more description as the code describes everything! 

Tags: C#

comments powered by Disqus