Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sending Email with attached file (image)

My method sends an email using a SMTP Relay Server.

Everything works fine (the email gets sent), except for that the attached file (the image) is somehow compressed/notexistent and not able to retrieve from the email.

The method looks like this:

public static bool SendEmail(HttpPostedFileBase uploadedImage)
        {
            try
            {              
                var message = new MailMessage() //To/From address
                {
                    Subject = "This is subject."
                    Body = "This is text."
                };                             

                    if (uploadedImage != null && uploadedImage.ContentLength > 0)
                    {
                        System.Net.Mail.Attachment attachment;
                        attachment = new System.Net.Mail.Attachment(uploadedImage.InputStream, uploadedImage.FileName);
                        message.Attachments.Add(attachment);
                    }
                message.IsBodyHtml = true;

                var smtpClient = new SmtpClient();
                //SMTP Credentials
                smtpClient.Send(message);
                return true;
            }
            catch (Exception ex)
            {
            //Logg exception
                return false;
            }
        }
  1. The uploadedImage is not null.
  2. ContentLength is 1038946 bytes (correct size).

However, the email that is being sent contains the image as an attachment with correct filename, although it's size is 0 bytes.

What am I missing?

like image 826
ChrisRun Avatar asked Oct 31 '22 11:10

ChrisRun


1 Answers

The second parameter of constructor of System.Net.Mail.Attachment is not the file name. It's the content type. And perhaps ensure your stream position is 0 before to create attachment

like image 172
Troopers Avatar answered Nov 12 '22 22:11

Troopers