Philip Voloshin
Philip Voloshin

Reputation: 111

Email sending with attachment issue

I am trying to send an email message to different users (with an attachment). The email is being sent, but only one user receives the attachment (image file). Other recipients receive something like empty picture, or picture with name and zero bytes.

I don't really understand what is going wrong. Here is code that I used for sending emails:

public void SendWithFile(string recipientName, string body, string subject = null, HttpPostedFileBase emailFile = null)
{
    using (var msg = new MailMessage())
    {
        msg.To.Add(recipientName);
        msg.From = new MailAddress(ConfigurationManager.AppSettings["MailServerSenderAdress"]);
        msg.Subject = subject;
        msg.Body = body;
        msg.SubjectEncoding = Encoding.UTF8;
        msg.BodyEncoding = Encoding.UTF8;
        msg.IsBodyHtml = true;
        msg.Priority = MailPriority.Normal;

        using (Attachment data = new Attachment(emailFile.InputStream, Path.GetFileName(emailFile.FileName), emailFile.ContentType))
        {
            msg.Attachments.Add(data);

            using (var client = new SmtpClient())
            {
                //client configs
                try
                {
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}

and here is where I call the send email method:

foreach (var recipent in notesRecipients)
{
   if (!string.IsNullOrEmpty(userEmail))
   {
       if (emailFile != null)
          emailService.SendWithFile(userEmail, message, null, emailFile);
    }
}

Upvotes: 0

Views: 252

Answers (1)

Rey
Rey

Reputation: 4002

You have to seek the stream from the beginning like below before you send the attachment:

emailFile.InputStream.Position = 0;

For more info you can refer to this question here: link

Upvotes: 0

Related Questions