Reputation: 21
I have an excel file in my solution with name Book1.xlsx. I want to attach it to my mail and send it.
Here is my code:
public void mailer()
{
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "Si9369787348");
smtp.EnableSsl = true;
MailMessage mail = new MailMessage();
string FileName = System.IO.Path.GetFileName(Server.MapPath("excel/Book1.xlsx"));
mail.Attachments.Add(new Attachment(FileName));
mail.IsBodyHtml = true;
mail.Subject = "status";
mail.Body = "Today's list " + "<br/>" + Label1.Text;
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
smtp.Send(mail);
}
But I get following error:
An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: Could not find file 'C:\Program Files\IIS Express\Book1.xlsx'.
What am I doing wrong?
Upvotes: 1
Views: 6687
Reputation: 572
try this code in filepath
string path = Path.Combine(HttpRuntime.AppDomainAppPath, "excel/Book1.xlsx");
attachment = new System.Net.Mail.Attachment(path);
Upvotes: 0
Reputation: 151586
You're passing just the filename, which resolves to a relative path, being C:\Program Files\IIS Express
because your code is running in IIS Express:
string FileName = System.IO.Path.GetFileName(Server.MapPath("excel/Book1.xlsx"));
mail.Attachments.Add(new Attachment(FileName));
You need to pass the full path, simply remove the GetFileName()
:
string FileName = Server.MapPath("excel/Book1.xlsx");
mail.Attachments.Add(new Attachment(FileName));
Upvotes: 2