.NET Core-附件导致发送邮件失败

时间:2018-11-02 16:14:55

标签: c# .net-core smtp

我有以下代码,当我没有attachment.add行时可以使用。 (我已清空地址和密码)。

请帮助,我猜我附件有问题,我不确定是什么!

内部异常是

  

{System.ObjectDisposedException:无法访问已处置的对象。   对象名称:“ ReferenceReadStream”。在   System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)位于   System.Net.Mail.Message.EndSend(IAsyncResult asyncResult)位于   System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult结果)}

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

2 个答案:

答案 0 :(得分:0)

我认为流需要可读,添加

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

答案 1 :(得分:0)

我认为流没有读到结尾:

尝试:

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

    var smtpClient = new SmtpClient

也许您必须在调用SendEmail之前阅读filcontent