C # Sending email with attachment (image)

My method sends an email using SMTP Relay Server.

Everything works fine (an email is sent), except that the attached file (image) is somehow compressed / does not exist and cannot be extracted from the email.

The method is as follows:

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; } } 
  • UploadedImage is not null.
  • ContentLength - 1038946 bytes (correct size).

However, the sent e-mail contains an image as an attachment with the correct file name, although its size is 0 bytes.

What am I missing?

+5
source share
2 answers

The second parameter to the System.Net.Mail.Attachment constructor is not a file name. This is a type of content . And maybe make sure your stream position is 0 to create an attachment

+1
source

@ChrisRun,

  • You should change the HttpPostedFileBase parameter as byte [], for example. This way you can reuse your class in more places.
  • Try changing the filename for ContentType and add MediaTypeNames.Image.Jpeg.
  • Also add a use directive to host MailMessage and SmtpClient

      using (var message = new MailMessage { From = new MailAddress(" from@gmail.com "), Subject = "This is subject.", Body = "This is text.", IsBodyHtml = true, To = { " to@someDomain.com " } }) { if (imageFile != null && imageFile.ContentLength > 0) { message.Attachments.Add(new Attachment(imageFile.InputStream, imageFile.ContentType, MediaTypeNames.Image.Jpeg)); } using (var client = new SmtpClient("smtp.gmail.com") { Credentials = new System.Net.NetworkCredential("user", "password"), EnableSsl = true }) { client.Send(message); } } 

Greetings

+1
source

Source: https://habr.com/ru/post/1240604/


All Articles