How to change email attachment's file's extension?

Ionut Dragomir 26 Reputation points
2022-04-19T12:03:45.333+00:00

I am using this class to send an email with a PDF attachment. The class has the following code:

using System.IO;  
using System.Net;  
using System.Net.Mail;  
using DevExpress.XtraPrinting;  
using DevExpress.XtraReports.Web.WebDocumentViewer;  
using DevExpress.XtraReports.Web.WebDocumentViewer.DataContracts;  
  
namespace DocumentOperationServiceSample.Services  
{  
    public class CustomDocumentOperationService : DocumentOperationService {  
        public override bool CanPerformOperation(DocumentOperationRequest request)  
        {  
            return true;  
        }  
  
        public override DocumentOperationResponse PerformOperation(DocumentOperationRequest request, PrintingSystemBase initialPrintingSystem, PrintingSystemBase printingSystemWithEditingFields)  
        {  
            using (var stream = new MemoryStream()) {  
                printingSystemWithEditingFields.ExportToPdf(stream);  
                stream.Position = 0;  
                var mailAddress = new MailAddress(request.CustomData);  
                var recipients = new MailAddressCollection() { mailAddress };  
                var attachment = new Attachment(stream, System.Net.Mime.MediaTypeNames.Application.Pdf);  
                return SendEmail(recipients, "Enter_Mail_Subject", "Enter_Message_Body", attachment);  
            }  
        }  
  
        DocumentOperationResponse SendEmail(MailAddressCollection recipients, string subject, string messageBody, Attachment attachment) {  
            string SmtpHost = null;  
            int SmtpPort = -1;  
            if (string.IsNullOrEmpty(SmtpHost) || SmtpPort == -1) {  
                return new DocumentOperationResponse { Message = "Please configure the SMTP server settings." };  
            }  
  
            string SmtpUserName = "Enter_Sender_User_Account";  
            string SmtpUserPassword = "Enter_Sender_Password";  
            string SmtpFrom = "Enter_Sender_Address";  
            string SmtpFromDisplayName = "Enter_Sender_Display_Name";  
            using (var smtpClient = new SmtpClient(SmtpHost, SmtpPort))  
            {  
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;  
                smtpClient.EnableSsl = true;  
  
                if (!string.IsNullOrEmpty(SmtpUserName))  
                {  
                    smtpClient.Credentials = new NetworkCredential(SmtpUserName, SmtpUserPassword);  
                }  
  
                using (var message = new MailMessage())  
                {  
                    message.Subject = subject.Replace("\r", "").Replace("\n", "");  
                    message.IsBodyHtml = true;  
                    message.Body = messageBody;  
                    message.From = new MailAddress(SmtpFrom, SmtpFromDisplayName);  
  
                    foreach (var item in recipients)  
                    {  
                        message.To.Add(item);  
                    }  
  
                    try  
                    {  
                        if (attachment != null)  
                        {  
                            message.Attachments.Add(attachment);  
                        }  
                        smtpClient.Send(message);  
                        return new DocumentOperationResponse  
                        {  
                            Succeeded = true,  
                            Message = "Mail was sent successfully"  
                        };  
                    }  
                    catch (SmtpException e)  
                    {  
                        return new DocumentOperationResponse  
                        {  
                            Message = "Sending an email message failed."  
                        };  
                    }  
                    finally  
                    {  
                        message.Attachments.Clear();  
                    }  
                }  
            }  
        }  
  
        protected string RemoveNewLineSymbols(string value)  
        {  
            return value;  
        }  
    }  
}   

It works fine, but when I receive the email it has attached an document named application/pdf. I was trying to find out where the document's name comes from. As you can see in the below image, when I add the application type PDF, it appears exactly what I get attached in email.
194253-image.png
The problem is that application/pdf cannot be opened with any PDF viewer app. I have to rename the document to application.pdf in order to be able to open it. Is there a way to change application/pdf with application.pdf?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,312 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 49,246 Reputation points
    2022-04-19T14:54:13.66+00:00

    I'm a little confused as to what the actual error is you're getting. It sounds like the attachment filename is just wrong. It is using the MIME type and not a filename.

    The issue with your code is that you're using the wrong constructor of Attachment. It's easy to do. The version you're calling requires the filename as the second parameter and the media type is the third parameter. You're passing the media type as the filename.

       new Attachment(stream, "report.pdf", System.Net.Mime.MediaTypeNames.Application.Pdf);  
    

    Alternatives to fix this going forward is to use the ContentType overload or using the parameter names in the calls.


2 additional answers

Sort by: Most helpful
  1. Sudipta Chakraborty - MSFT 1,101 Reputation points Microsoft Employee
    2022-04-19T13:28:39.48+00:00

    @Ionut Dragomir :

    To solve the issue :

    1) You can convert or write the Memory stream object to a file using:

    memoryStream.CopyTo(fileStream);

    2) Then you can attach the file to the email message using :

    // Create the file attachment for this email message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);

    Reference:
    https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.attachment?view=net-6.0#examples

    0 comments No comments

  2. Yijing Sun-MSFT 7,071 Reputation points
    2022-04-20T03:30:38.223+00:00

    Hi @Ionut Dragomir ,
    I think you could try to overload the

    Attachment pdfAttachment = new Attachment(stream,"application.pdf");  
    pdfAttachment.ContentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Pdf;  
    Msg.Attachments.Add(pdfAttachment);  
    

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments