Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a nice name for an e-mail (System.Net.Mail.SmtpClient) attachment

I'm sending attachments using the System.Net.Mail.SmtpClient in C#.
The attachment names are the same as the name of the file I pass into the attachment constructor

myMail.Attachments.Add(new Attachment(attachmentFileName));

How would I go about setting a "nice" name for the attachment? The names I currently have are basically numeric IDs indicating which occurrence of a report is attached. My users are looking for something more friendly like "results.xls".

like image 543
Brad Bruce Avatar asked Jun 24 '09 17:06

Brad Bruce


People also ask

Is SmtpClient obsolete?

The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.

How do I add an attachment in system net email?

To add an attachment to a mail message, add it to the MailMessage. Attachments collection. Attachment content can be a String, Stream, or file name. You can specify the content in an attachment by using any of the Attachment constructors.

What is SmtpClient C#?

SMTP Client in C# and VB.NETThe Simple Mail Transfer Protocol (SMTP) is the only standard protocol for sending mail messages over the Internet. GemBox. Email enables you to work with the SMTP protocol in C# and VB.NET using an SmtpClient class.


2 Answers

See Attachment.Name Property:

Gets or sets the MIME content type name value in the content type associated with this attachment.

You can set the Attachment .Name property to anything you like. In the example inside the last link, you could have :

// Create  the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
data.Name = "VeryNiceName.dat"; //(not in original example)
...
message.Attachments.Add(data);
like image 177
gimel Avatar answered Sep 21 '22 00:09

gimel


Save the attachment to the temp folder with the desired name then attach it. Don't forget to delete it after you send the email so the temp folder doesn't grow too large.

Edit: The accepted answer is much better but I'll leave this here for others that go down the same thought path and see how wrong it is.

like image 21
Paul Alexander Avatar answered Sep 18 '22 00:09

Paul Alexander