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("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="492f3b2624092f2626672a2624">[email protected]</a>", "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0a11113e181111501d1113">[email protected]</a>");
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("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bed8ccd1d3fed8d1d190ddd1d3">[email protected]</a>", "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01756e41676e6e2f626e6c">[email protected]</a>");
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);
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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:
Method 3
An extension to the Solution supplied in the original question also correctly cleans up an attachments that may also require disposal.
public event EventHandler EmailSendCancelled = delegate { };
public event EventHandler EmailSendFailure = delegate { };
public event EventHandler EmailSendSuccess = delegate { };
...
MemoryStream mem = new MemoryStream();
try
{
thisReport.ExportToPdf(mem);
// Create a new attachment and put the PDF report into it.
mem.Seek(0, System.IO.SeekOrigin.Begin);
//Attachment att = new Attachment(mem, "MyOutputFileName.pdf", "application/pdf");
Attachment messageAttachment = new Attachment(mem, thisReportName, "application/pdf");
// Create a new message and attach the PDF report to it.
MailMessage message = new MailMessage();
message.Attachments.Add(messageAttachment);
// Specify sender and recipient options for the e-mail message.
message.From = new MailAddress(NOES.Properties.Settings.Default.FromEmailAddress, NOES.Properties.Settings.Default.FromEmailName);
message.To.Add(new MailAddress(toEmailAddress, NOES.Properties.Settings.Default.ToEmailName));
// Specify other e-mail options.
//mail.Subject = thisReport.ExportOptions.Email.Subject;
message.Subject = subject;
message.Body = body;
// Send the e-mail message via the specified SMTP server.
SmtpClient smtp = new SmtpClient();
smtp.SendCompleted += SmtpSendCompleted;
smtp.SendAsync(message, message);
}
catch (Exception)
{
if (mem != null)
{
mem.Dispose();
mem.Close();
}
throw;
}
}
private void SmtpSendCompleted(object sender, AsyncCompletedEventArgs e)
{
var message = e.UserState as MailMessage;
if (message != null)
{
foreach (var attachment in message.Attachments)
{
if (attachment != null)
{
attachment.Dispose();
}
}
message.Dispose();
}
if (e.Cancelled)
EmailSendCancelled?.Invoke(this, EventArgs.Empty);
else if (e.Error != null)
{
EmailSendFailure?.Invoke(this, EventArgs.Empty);
throw e.Error;
}
else
EmailSendSuccess?.Invoke(this, EventArgs.Empty);
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0