简体   繁体   中英

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);
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM