Skip to content

Instantly share code, notes, and snippets.

@joshi-kumar
Last active December 22, 2021 05:54
Show Gist options
  • Save joshi-kumar/6920d5b19afae49dc93eee311737a1e2 to your computer and use it in GitHub Desktop.
Save joshi-kumar/6920d5b19afae49dc93eee311737a1e2 to your computer and use it in GitHub Desktop.
Send Email method with attachment (with bcc option)
static public void Send(string emails, string subject, string message, bool isHTML=true, params string[] attachmentPaths)
{
try
{
using (var client = new SmtpClient())
{
var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
// email message setting
MailMessage msg = new MailMessage();
msg.From = new MailAddress(section.Network.UserName, "Email address with title");
foreach (string email in emails.Split(','))
{
msg.To.Add(new MailAddress(email.Trim()));
}
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = isHTML;
if (!String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["BccAddress"]))
msg.Bcc.Add(new MailAddress(System.Configuration.ConfigurationManager.AppSettings["BccAddress"]));
#region To add attachments within the email
if (attachmentPaths != null)
{
string appPath = HostingEnvironment.ApplicationPhysicalPath;
if (attachmentPaths.Length > 0)
{
foreach (string attachmentPath in attachmentPaths)
{
// check if path is complete file path.
if (!string.IsNullOrEmpty(attachmentPath) && File.Exists(attachmentPath))
{
msg.Attachments.Add(new Attachment(attachmentPath));
}
// check if directory exist for this path.
else if (!string.IsNullOrEmpty(attachmentPath) && Directory.Exists(attachmentPath))
{
string[] files = Directory.GetFiles(attachmentPath);
foreach (string fileName in files)
{
msg.Attachments.Add(new Attachment(fileName));
}
}
}
}
else if (!string.IsNullOrEmpty(appPath + section.Network.TargetName) && File.Exists(appPath + section.Network.TargetName))
{
msg.Attachments.Add(new Attachment(appPath + section.Network.TargetName));
}
}
#endregion
// smtp client setting.
client.Host = section.Network.Host;
client.Port = section.Network.Port;
client.UseDefaultCredentials = false;
client.EnableSsl = section.Network.EnableSsl;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(section.Network.UserName, section.Network.Password);
client.Send(msg);
}
}
catch (Exception e)
{
WriteLog(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment