Send an Email with attachment to Multiple Recipients using ASP.Net



Get all email address to list from Database. Here I am using LINQ to SQL to get Email Address from Database.

DBDataContext DB = new DBDataContext();

string KitName = rdoAffectedKit.SelectedItem.Text.ToString();

var query = from p in DB.KitMembers
where p.KitID == (from kit in DB.Kits
where kit.KitName == KitName
select kit.KitID).First()
select p;

List _emailList = new List();
foreach (var obj in query)
_emailList.Add(obj.MemberEmail);
//MemberEmail is the DB filed, which holds the email address

SendEmail(_emailList);
//Send Email is the method, which sends email to all recipients


protected void SendEmail(List _Recipients)
{
MailMessage message = new MailMessage();

//Add All Recipients Address to Mail Message
foreach(string _toAddress in _Recipients)
message.To.Add(new MailAddress(_toAddress));

message.From = new MailAddress(ConfigurationManager.AppSettings ["From"].ToString());
message.Subject = ConfigurationManager.AppSettings["Subject"].ToString();
message.Body = ConfigurationManager.AppSettings["Body"].ToString();

//SMTP Server Configuration
string SMTPPort = ConfigurationManager.AppSettings["Port"].ToString();
string SMTPServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
SmtpClient client = new SmtpClient(SMTPServer, Convert.ToInt32(SMTPPort));
client.Credentials = CredentialCache.DefaultNetworkCredentials;

//Attach Xls Template
string source = Server.MapPath("ECRTest.xlsm");
Attachment data = new Attachment(source);
message.Attachments.Add(data);

try
{
//Sends an Email to Recipients
client.Send(message);
Response.Write("An E-Mail has been sent");
}
catch
{
Response.Write("Error: Mail has not been sent");
}
}

I have maintained From Address, Subject, Body, SMTPServer and Port maintained in Web.Config File.

Comments

Popular posts from this blog

Windows Azure Package Build Error: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Resource ID : 1. The request limit for the database is 180 and has been reached.

How to get Client's Location using IPAddress