SMTPException One of the threads is already in use and cannot be reset at the beginning

When I try to send an email with an attachment with multiple recipients through my C # code, I get a System.Net.Mail.SmtpException message that says, "Failed to send mail." Internal exception: "One of the threads is already in use and cannot be reset at the beginning."

I understand that such a mistake may be due to my attachment. I created my binding in another class since -

Attatchment file; string fileContents = File.ReadAllText(fileName); file = Attachment.CreateAttachmentFromString(fileContents, fileName); 

I send it in this format to my class, which sends an email. In this class, the following happens:

 try { email.Subject = subject; email.Body = body; if (file != null) { email.Attachments.Add(file); } _smtpClient.Send(email); } catch { mailSent = false; } 

Mail is always sent to the first recipient, but not for all others. Any ideas why this could be happening?

+6
source share
2 answers

Inside the Attachment class, it must use Stream to store data. Some types of threads do not allow you to reset the position back to the beginning and will throw an InvalidOperationException with the message that you see above.

Your decisions:

  • Send one letter, but put all recipients in the Bcc field.
  • Create an attachment for each letter you send - do not use the same object every time.
  • This may not work, but you can try using the constructor for Attachment , which takes a stream as a parameter instead of a string. Put all your string data in a MemoryStream , which allows reordering. For instance:

     public Stream StringToStream(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } 

    Then this:

     var stream = StringToStream(File.ReadAllText(fileName)); Attatchment file = new Attachment(stream, fileName); 

Note. You are not initializing the attachment object correctly. In the constructor

+7
source

In our case, it was an instance of LinkedResource (a file attachment embedded in an email as an embedded image), which was RE-USED for several messages. And the messages were .Dispose 'd after sending - which closed all the underlying threads.

I think this essentially boils down to @DavidG's answer by simply adding my two cents - remember to check the embedded resources, not just the attachments.

0
source

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


All Articles