This small snippets can be used in your project if you need to deliver many emails using c# without caring if the receiver's email is defined in the recipients and in the Carbon Copy (Cc) or in the Blind CArbon Copy (Bcc) twice.
This method simply checks every time if an email is present in the To header is also contained in the Cc and/or in the Bcc.
Bulk emailing is also supported: just separate you emails, using a separator character (in my case is a comma ',').
public static void SendMail(string Subject, string Body, bool IsHtml, string From, string To, string Cc, string Bcc)
{
const char SEPARATOR = ',';
string[] Tos = new string[0];
string[] Ccs = new string[0];
string[] Bccs = new string[0];
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(From);
mailMessage.Subject = Subject;
mailMessage.Body = Body;
mailMessage.IsBodyHtml = IsHtml;
if (!String.IsNullOrEmpty(To))
Tos = To.Split(new char[] { SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
if (!String.IsNullOrEmpty(Cc))
Ccs = Cc.Split(new char[] { SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
if (!string.IsNullOrEmpty(Bcc))
Bccs = Bcc.Split(new char[] { SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in Tos)
{
mailMessage.To.Add(new MailAddress(item));
}
foreach (string item in Ccs)
{
if (!isMailCointained(item, Tos))
{
mailMessage.CC.Add(new MailAddress(item));
}
}
foreach (string item in Bccs)
{
if (!isMailCointained(item, Tos) && !isMailCointained(item ,Ccs))
{
mailMessage.Bcc.Add(new MailAddress(item));
}
}
try
{
SmtpClient smtpClient = new SmtpClient();
// add your smtp server!
smtpClient.Host = ConfigurationManager.AppSettings["YOUR EMAIL SERVER"];
smtpClient.Send(mailMessage);
}
catch(Exception exc){// add your exception handlers.. }
}
private static bool isMailCointained(string mail, string[] mails)
{
bool toRet = false;
foreach (var item in mails)
{
if (mail == item)
return true;
}
return toRet;
}
If you call the SendMail method using:
SendMail("Hello", "<h3>Hello from myrocode!</h3>", true,
"myEmail@a.com", "a@a.com,b@a.com,c@a.com", "z@a.com,b@a.com", "x@a.com,y@a.com,z@a.com");
You email will be deliverd with the following headers:
To: a@a.com
b@a.com
c@a.com
Cc:z@a.com
Bcc:x@a.com
y@a.com
this post is nothing special.. but can be usefull for a fast refernce or a copy & paste code snippet for your project.