riccardo
riccardo

Reputation: 31

Set Email Attachment name in C# with System.Web.Mail

I add an attachment like this:

System.Web.Mail.MailAttachment attachment = new System.Web.Mail.MailAttachment(AttachmentPath);   

System.Web.Mail.MailMessage mailMsg = new System.Web.Mail.MailMessage();
....
mailMsg.Attachments.Add(attachment);

But I want to make it attach as a different name, the actual file name is very long and confusing because it is a temporary file. I would like it to attach such as "SalesOrderNo1.pdf", is there an easy way to do this without having to make a copy of the file with high risk of file name collision?

(I cannot use System.Net.Mail because I have to connect with servers that use Implicit SSL but System.Net.Mail does not support it.)

Upvotes: 3

Views: 5059

Answers (2)

Kiran Hegde
Kiran Hegde

Reputation: 3681

Use STMP Mail instead. System.Web.Mail.MailMessage is obsolete. You can use the smtp mail message using the following code. With this you can change the attachment name. This is the complete code for sending email using smtp client. Please change all the parameters as required

                SmtpClient smtpClient = new SmtpClient();
                MailMessage message = new MailMessage();
                smtpClient.Host = "host name";
                smtpClient.Port = 25;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential("user name", "password");
                smtpClient.EnableSsl = false;
                message.IsBodyHtml = true;

                message.Priority = MailPriority.Normal;
                message.From = new MailAddress("from email address");
                string file = @"your file complete path";
                Attachment data = new Attachment(file);
                message.Attachments.Add(data);
                data.Name = "newfilename";
                message.To.Add("testemailaddress");
                message.Subject = "test email";
                message.Body = "test email";
                smtpClient.Send(message);

Upvotes: 3

krillgar
krillgar

Reputation: 12805

You will have to rename the file. If you want to avoid file name collisions, you could always have a temp folder that you copy the files to and rename them in there. Then attach this new file to your email, send the email, and regardless of a successful send or not, delete the file at the end of your method.

Regardless, deleting the attachments when you're done emailing them out is probably a good practice to get into anyway unless you need to keep the files for some sort of auditing purposes.

Upvotes: 2

Related Questions