views:

3120

answers:

3

Hi,

I am using a service component through ASP.NET MVC. I would like to send the email in a asynchronous way to let the user do other stuff without having to wait for the sending.

When I send a message without attachments it works fine. When I send a message with at least one in-memory attachment it fails.

So, I would like to know if it is possible to use an async method with in-memory attachments.

Here is the sending method


    public static void Send() {

     MailMessage message = new MailMessage("[email protected]", "[email protected]");
     using (MemoryStream stream = new MemoryStream(new byte[64000])) {
      Attachment attachment = new Attachment(stream, "my attachment");
      message.Attachments.Add(attachment);
      message.Body = "This is an async test.";

      SmtpClient smtp = new SmtpClient("localhost");
      smtp.Credentials = new NetworkCredential("foo", "bar");
      smtp.SendAsync(message, null);
     }
    }

Here is my current error


System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.NotSupportedException: Stream does not support reading.
   at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)
   at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult)
   at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)
   --- End of inner exception stack trace ---


Solution

    public static void Send()
    {

            MailMessage message = new MailMessage("[email protected]", "[email protected]");
            MemoryStream stream = new MemoryStream(new byte[64000]);
            Attachment attachment = new Attachment(stream, "my attachment");
            message.Attachments.Add(attachment);
            message.Body = "This is an async test.";
            SmtpClient smtp = new SmtpClient("localhost");
            //smtp.Credentials = new NetworkCredential("login", "password");

            smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                    if (e.Error != null)
                    {
                            System.Diagnostics.Trace.TraceError(e.Error.ToString());

                    }
                    MailMessage userMessage = e.UserState as MailMessage;
                    if (userMessage != null)
                    {
                            userMessage.Dispose();
                    }
            };

            smtp.SendAsync(message, message);
    }
A: 

I have tried your function and it works even for email with in memory attachments. But here are some remarks:

  • What type of attachments did you try to send ? Exe ?
  • Are both sender and receiver on the same email server ?
  • You should “catch” exception and not just swallow it, than you will get more info about your problem.
  • What does the exception says ?

  • Does it work whan you use Send instead of SendAsync ? You are using 'using' clause and closing Stream before email is sent.

Here is good text about this topic:

Sending Mail in .NET 2.0

Robert Vuković
I should put more code, sorry about that.Let me edit the sample to give you more information.
labilbe
Could it be possible that the Async calls running in the VS Dev Server isn't actually called Async. My fuzzy memory is trying to remember something said somewhere about the VS Dev Web Server is single threaded?
Redbeard 0x0A
+1  A: 

This works for me:

public void SendFile(String fromAddress, String toAddress, String fileName, String messageBody)
    {
        try
        {
            SmtpClient smtpClient = new SmtpClient("localhost", 2525);
            MailMessage message = new MailMessage();

            message.IsBodyHtml = false;
            message.BodyEncoding = Encoding.Default;

            using (FileStream fileStream = File.OpenRead(fileName))
            {

                MailAddress messageTo = new MailAddress(toAddress);
                message.To.Add(messageTo);

                MailAddress messageFrom = new MailAddress(fromAddress);
                message.From = messageFrom;

                message.Body = messageBody;

                Attachment messageAttachment = new Attachment(fileStream, Path.GetFileName(fileName));
                message.Attachments.Add(messageAttachment);
            }

            smtpClient.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    System.Diagnostics.Trace.TraceError(e.Error.ToString());
                }
            };

            smtpClient.SendAsync(message, null);
        }
        catch (SmtpException smtpEx)
        {
            System.Diagnostics.Trace.TraceError(smtpEx.ToString());
        }
    }
slf
Can you try with my new code sample please?
labilbe
+5  A: 

Don't use "using" here. You are destroying the memory stream immediately after calling SendAsync, e.g. probably before SMTP gets to read it (since it's async). Destroy your stream in the callback.

liggett78
Thank you you saved my day!
labilbe
Thanks - this simple and consise comment helped me with a similar issue when working with a loop that adds multiple LinkedResources to an AlternativeView using the ctor that takes a stream. Kept getting stream closed exception. Was in a "must use using statement" rut.
J M