.NET Core - Attachment causing Failure Sending Mail











up vote
0
down vote

favorite












I have the following code, which works when I don't have the attachment.add line. (I've blanked out the addresses & password).



Please help, I guess I'm doing something wrong with the attachment I'm just not sure what!



The inner exception is




{System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ReferenceReadStream'. at
System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}




    [HttpPost]
public async Task<String> PostProfilePicture(IFormFile file, int ID)
{
var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
try
{
var stream = file.OpenReadStream();
await sendEmail(stream, name);
}
catch (Exception ex)
{
return ex.Message.ToString();
}

return ""
}

public async Task sendEmail(Stream stream, String filename){
var attachment = new Attachment(stream, filename);

var smtpClient = new SmtpClient

{
Host = "smtp.gmail.com", // set your SMTP server name here
Port = 587, // Port
EnableSsl = true,
Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
};

var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


message.Subject = "Hello Alec!!";
message.Body = "How are you doing.";
message.Attachments.Add(attachment);




await smtpClient.SendMailAsync(message);
}
}









share|improve this question
























  • The error message was in the title, "Failure Sending Mail"
    – Alec.
    Nov 2 at 16:26










  • Oops. {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'ReferenceReadStream'. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}
    – Alec.
    Nov 2 at 16:29















up vote
0
down vote

favorite












I have the following code, which works when I don't have the attachment.add line. (I've blanked out the addresses & password).



Please help, I guess I'm doing something wrong with the attachment I'm just not sure what!



The inner exception is




{System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ReferenceReadStream'. at
System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}




    [HttpPost]
public async Task<String> PostProfilePicture(IFormFile file, int ID)
{
var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
try
{
var stream = file.OpenReadStream();
await sendEmail(stream, name);
}
catch (Exception ex)
{
return ex.Message.ToString();
}

return ""
}

public async Task sendEmail(Stream stream, String filename){
var attachment = new Attachment(stream, filename);

var smtpClient = new SmtpClient

{
Host = "smtp.gmail.com", // set your SMTP server name here
Port = 587, // Port
EnableSsl = true,
Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
};

var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


message.Subject = "Hello Alec!!";
message.Body = "How are you doing.";
message.Attachments.Add(attachment);




await smtpClient.SendMailAsync(message);
}
}









share|improve this question
























  • The error message was in the title, "Failure Sending Mail"
    – Alec.
    Nov 2 at 16:26










  • Oops. {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'ReferenceReadStream'. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}
    – Alec.
    Nov 2 at 16:29













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have the following code, which works when I don't have the attachment.add line. (I've blanked out the addresses & password).



Please help, I guess I'm doing something wrong with the attachment I'm just not sure what!



The inner exception is




{System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ReferenceReadStream'. at
System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}




    [HttpPost]
public async Task<String> PostProfilePicture(IFormFile file, int ID)
{
var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
try
{
var stream = file.OpenReadStream();
await sendEmail(stream, name);
}
catch (Exception ex)
{
return ex.Message.ToString();
}

return ""
}

public async Task sendEmail(Stream stream, String filename){
var attachment = new Attachment(stream, filename);

var smtpClient = new SmtpClient

{
Host = "smtp.gmail.com", // set your SMTP server name here
Port = 587, // Port
EnableSsl = true,
Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
};

var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


message.Subject = "Hello Alec!!";
message.Body = "How are you doing.";
message.Attachments.Add(attachment);




await smtpClient.SendMailAsync(message);
}
}









share|improve this question















I have the following code, which works when I don't have the attachment.add line. (I've blanked out the addresses & password).



Please help, I guess I'm doing something wrong with the attachment I'm just not sure what!



The inner exception is




{System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'ReferenceReadStream'. at
System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at
System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}




    [HttpPost]
public async Task<String> PostProfilePicture(IFormFile file, int ID)
{
var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
try
{
var stream = file.OpenReadStream();
await sendEmail(stream, name);
}
catch (Exception ex)
{
return ex.Message.ToString();
}

return ""
}

public async Task sendEmail(Stream stream, String filename){
var attachment = new Attachment(stream, filename);

var smtpClient = new SmtpClient

{
Host = "smtp.gmail.com", // set your SMTP server name here
Port = 587, // Port
EnableSsl = true,
Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
};

var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


message.Subject = "Hello Alec!!";
message.Body = "How are you doing.";
message.Attachments.Add(attachment);




await smtpClient.SendMailAsync(message);
}
}






c# .net-core smtp






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 2 at 16:30

























asked Nov 2 at 16:14









Alec.

3,46741749




3,46741749












  • The error message was in the title, "Failure Sending Mail"
    – Alec.
    Nov 2 at 16:26










  • Oops. {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'ReferenceReadStream'. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}
    – Alec.
    Nov 2 at 16:29


















  • The error message was in the title, "Failure Sending Mail"
    – Alec.
    Nov 2 at 16:26










  • Oops. {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'ReferenceReadStream'. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}
    – Alec.
    Nov 2 at 16:29
















The error message was in the title, "Failure Sending Mail"
– Alec.
Nov 2 at 16:26




The error message was in the title, "Failure Sending Mail"
– Alec.
Nov 2 at 16:26












Oops. {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'ReferenceReadStream'. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}
– Alec.
Nov 2 at 16:29




Oops. {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'ReferenceReadStream'. at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult) at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult) at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)}
– Alec.
Nov 2 at 16:29












2 Answers
2






active

oldest

votes

















up vote
0
down vote













I think the stream is no read to end:



Try:



    var fileContent = stream.ReadToEnd();
var attachment = new Attachment(fileContent, filename);

var smtpClient = new SmtpClient


Perhaps You have to read the filcontent before calling SendEmail






share|improve this answer




























    up vote
    0
    down vote













    I think the stream needs to be readable, add



    [HttpPost]
    public async Task<String> PostProfilePicture(IFormFile file, int ID)
    {
    var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
    try
    {
    await sendEmail(file, name); //send the file not the open read stream
    }
    catch (Exception ex)
    {
    return ex.Message.ToString();
    }

    return "";
    }



    public async Task sendEmail(IFormFile file, String filename){

    using(var stream = file.OpenReadStream()){ //You open your stream here
    var attachment = new Attachment(stream, filename);

    var smtpClient = new SmtpClient

    {
    Host = "smtp.gmail.com", // set your SMTP server name here
    Port = 587, // Port
    EnableSsl = true,
    Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
    };

    var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


    message.Subject = "Hello Alec!!";
    message.Body = "How are you doing.";
    message.Attachments.Add(attachment);

    await smtpClient.SendMailAsync(message);
    }
    }
    }





    share|improve this answer























    • My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
      – Alec.
      Nov 2 at 16:28










    • The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
      – Max
      2 days ago











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53122263%2fnet-core-attachment-causing-failure-sending-mail%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    I think the stream is no read to end:



    Try:



        var fileContent = stream.ReadToEnd();
    var attachment = new Attachment(fileContent, filename);

    var smtpClient = new SmtpClient


    Perhaps You have to read the filcontent before calling SendEmail






    share|improve this answer

























      up vote
      0
      down vote













      I think the stream is no read to end:



      Try:



          var fileContent = stream.ReadToEnd();
      var attachment = new Attachment(fileContent, filename);

      var smtpClient = new SmtpClient


      Perhaps You have to read the filcontent before calling SendEmail






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        I think the stream is no read to end:



        Try:



            var fileContent = stream.ReadToEnd();
        var attachment = new Attachment(fileContent, filename);

        var smtpClient = new SmtpClient


        Perhaps You have to read the filcontent before calling SendEmail






        share|improve this answer












        I think the stream is no read to end:



        Try:



            var fileContent = stream.ReadToEnd();
        var attachment = new Attachment(fileContent, filename);

        var smtpClient = new SmtpClient


        Perhaps You have to read the filcontent before calling SendEmail







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 3 at 19:34









        ivion

        12015




        12015
























            up vote
            0
            down vote













            I think the stream needs to be readable, add



            [HttpPost]
            public async Task<String> PostProfilePicture(IFormFile file, int ID)
            {
            var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
            try
            {
            await sendEmail(file, name); //send the file not the open read stream
            }
            catch (Exception ex)
            {
            return ex.Message.ToString();
            }

            return "";
            }



            public async Task sendEmail(IFormFile file, String filename){

            using(var stream = file.OpenReadStream()){ //You open your stream here
            var attachment = new Attachment(stream, filename);

            var smtpClient = new SmtpClient

            {
            Host = "smtp.gmail.com", // set your SMTP server name here
            Port = 587, // Port
            EnableSsl = true,
            Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
            };

            var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


            message.Subject = "Hello Alec!!";
            message.Body = "How are you doing.";
            message.Attachments.Add(attachment);

            await smtpClient.SendMailAsync(message);
            }
            }
            }





            share|improve this answer























            • My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
              – Alec.
              Nov 2 at 16:28










            • The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
              – Max
              2 days ago















            up vote
            0
            down vote













            I think the stream needs to be readable, add



            [HttpPost]
            public async Task<String> PostProfilePicture(IFormFile file, int ID)
            {
            var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
            try
            {
            await sendEmail(file, name); //send the file not the open read stream
            }
            catch (Exception ex)
            {
            return ex.Message.ToString();
            }

            return "";
            }



            public async Task sendEmail(IFormFile file, String filename){

            using(var stream = file.OpenReadStream()){ //You open your stream here
            var attachment = new Attachment(stream, filename);

            var smtpClient = new SmtpClient

            {
            Host = "smtp.gmail.com", // set your SMTP server name here
            Port = 587, // Port
            EnableSsl = true,
            Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
            };

            var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


            message.Subject = "Hello Alec!!";
            message.Body = "How are you doing.";
            message.Attachments.Add(attachment);

            await smtpClient.SendMailAsync(message);
            }
            }
            }





            share|improve this answer























            • My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
              – Alec.
              Nov 2 at 16:28










            • The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
              – Max
              2 days ago













            up vote
            0
            down vote










            up vote
            0
            down vote









            I think the stream needs to be readable, add



            [HttpPost]
            public async Task<String> PostProfilePicture(IFormFile file, int ID)
            {
            var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
            try
            {
            await sendEmail(file, name); //send the file not the open read stream
            }
            catch (Exception ex)
            {
            return ex.Message.ToString();
            }

            return "";
            }



            public async Task sendEmail(IFormFile file, String filename){

            using(var stream = file.OpenReadStream()){ //You open your stream here
            var attachment = new Attachment(stream, filename);

            var smtpClient = new SmtpClient

            {
            Host = "smtp.gmail.com", // set your SMTP server name here
            Port = 587, // Port
            EnableSsl = true,
            Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
            };

            var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


            message.Subject = "Hello Alec!!";
            message.Body = "How are you doing.";
            message.Attachments.Add(attachment);

            await smtpClient.SendMailAsync(message);
            }
            }
            }





            share|improve this answer














            I think the stream needs to be readable, add



            [HttpPost]
            public async Task<String> PostProfilePicture(IFormFile file, int ID)
            {
            var name = Guid.NewGuid().ToString("N").ToUpper() + ".png";
            try
            {
            await sendEmail(file, name); //send the file not the open read stream
            }
            catch (Exception ex)
            {
            return ex.Message.ToString();
            }

            return "";
            }



            public async Task sendEmail(IFormFile file, String filename){

            using(var stream = file.OpenReadStream()){ //You open your stream here
            var attachment = new Attachment(stream, filename);

            var smtpClient = new SmtpClient

            {
            Host = "smtp.gmail.com", // set your SMTP server name here
            Port = 587, // Port
            EnableSsl = true,
            Credentials = new NetworkCredential("xxxxxxx@gmail.com", "xxxxxxxx")
            };

            var message = new MailMessage("xxxxxxx@gmail.com", "xxxxxxx@gmail.com");


            message.Subject = "Hello Alec!!";
            message.Body = "How are you doing.";
            message.Attachments.Add(attachment);

            await smtpClient.SendMailAsync(message);
            }
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 30 mins ago

























            answered Nov 2 at 16:21









            Max

            1263




            1263












            • My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
              – Alec.
              Nov 2 at 16:28










            • The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
              – Max
              2 days ago


















            • My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
              – Alec.
              Nov 2 at 16:28










            • The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
              – Max
              2 days ago
















            My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
            – Alec.
            Nov 2 at 16:28




            My file comes from IFormFile, not sure how to implement that as I don't have a physical copy of the file.
            – Alec.
            Nov 2 at 16:28












            The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
            – Max
            2 days ago




            The exception ObjectDisposedException you have is related to the OpenReadStream() disposed object. You should send the IFormFile into your sendEmail() method instead of the stream and then openreadstream inside the SendEmail method.
            – Max
            2 days ago


















             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53122263%2fnet-core-attachment-causing-failure-sending-mail%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)