Reputation: 39
I am trying to send mail with excel attachment, the mail is getting sent but the attachment is in filename.xlsx.txt with no content (blank .txt file)
public void SendEmail()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.test.net");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
Attachment attachment;
attachment = new Attachment(File.Open(AppDomain.CurrentDomain.BaseDirectory + "result.xlsx", FileMode.Open), "result.xlsx");
attachment.ContentType = new ContentType("application/vnd.ms-excel");
mail.Attachments.Add(attachment);
SmtpClient client = new SmtpClient("smtp.test.net");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential credetial = new NetworkCredential("[email protected]", "******", "test.com");
client.UseDefaultCredentials = true;
client.EnableSsl = true;
try
{
System.Threading.Thread.Sleep(5000);
client.Send(mail);
}
catch (Exception e)
{
}
}
Email Attachment:
Upvotes: 0
Views: 2051
Reputation: 5306
I have a spreadsheet I attach like this... (Using your object name "mail")
mail.Attachments.Add(new Attachment(mail, "result.xls", "application/vnd.ms-excel"));
Instead of:
Attachment attachment;
attachment = new Attachment(File.Open(AppDomain.CurrentDomain.BaseDirectory + "result.xlsx", FileMode.Open), "result.xlsx");
attachment.ContentType = new ContentType("application/vnd.ms-excel");
mail.Attachments.Add(attachment);
Upvotes: 0
Reputation: 1554
You are not actually attaching the file, instead you are opening the file and saving it as result.xlsx
and this defaults to .txt
extension when saved. that explains why you are getting result.xlsx.txt
Instead of
Attachemnt attachment = new Attachment(File.Open(AppDomain.CurrentDomain.BaseDirectory + "result.xlsx", FileMode.Open), "result.xlsx");
attachment.ContentType = new ContentType("application/vnd.ms-excel");
Use
message.Attachments.Add(new Attachment(PathToAttachment));
Just pass the path to the file.
Again Am not sure you need the content type bit.
Upvotes: 2