locked
Fail to add multiple attachments to mail message in net core web app RRS feed

  • Question

  • User-1800993587 posted

    Hi,

    I try to construct and send an email message in a web net core app. The message need to have maximal 3 attachments, provided by the user who navigates the site. First is mandatory, and at least one from the two remaining attachments is also mandatory.

    If I attach only one (e.g. first) attachment, all is ok. But when I attach at least 2 attachments, I have an error.

    The relevant portions of code are bellow (the model, the view, and the controller). At the very bottom is the error:

    /*Relevant part of model*/
    
    public class Inscrieri.Inima.Models
    {
    //
            public IFormFile CopieCN { get; set; }
            public IFormFile CopieCIT { get; set; }
            public IFormFile CopieCIM { get; set; }
    //
    }
    
    
    /*Relevant part of view*/
    
    <div class="separator"></div>
                <div>
                    <strong>Certificat de Nastere Copil</strong><p> (in format *.jpg sau *.png):</p>
                </div>
                <div>
                    @Html.TextBoxFor(model => model.CopieCN, new { type = "file" })
                </div>
                <div>
                    <strong>Act de Identitate Tata:</strong><p> (in format *.jpg sau *.png):</p>
                </div>
                <div>
                    @Html.TextBoxFor(model => model.CopieCIT, new { type = "file" })
                </div>
                <div>
                    <strong>Act de Identitate Mama:</strong><p> (in format *.jpg sau *.png):</p>
                </div>
                <div>
                    @Html.TextBoxFor(model => model.CopieCIM, new { type = "file" })
                </div>
    <div class="separator"></div>
    
                <div class="clearfix"></div>
                <div>
                    <input type="submit" value="Trimite" />
                </div>
    
                <div class="separator"></div>
    
                <span style="color:green">@ViewBag.Message</span>
    
    
    /*Relevant part of controller*/
    
            [HttpPost]
            public IActionResult Index(EmailModel model)
            {
                using (MailMessage mm = new MailMessage("sender.email@gmail.com", "first.recipient@email.com, second.recipient@email.com"))
                {
                    mm.Subject = "Cerere de inscriere pentru: " + model.Prenume + " " + model.Nume;
                    mm.Body = "Va rog sa aprobati inscrierea copilului " + model.Prenume + " " + model.Nume + " nascut(a) la data de " + model.DataNasterii + ", avandu-i ca parinti pe " + model.NumeTata + " si " + model.NumeMama + " in grupa: " + model.Grupa+". "+ Environment.NewLine + "Locul de munca al parintilor: " + model.LocDeMunca;
                    mm.IsBodyHtml = true;
                    mm.Priority = MailPriority.High;
    
    
                    //atasam CN copil
                    if (model.CopieCN.Length > 0)
                    {
                        string fileNameCN = Path.GetFileName(model.CopieCN.FileName);
                        Attachment file1 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCN, MediaTypeNames.Application.Octet);
                        mm.Attachments.Add(file1);
                        //file1.Dispose();
                        //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCN, MediaTypeNames.Application.Octet));
                    }
                    //atasam CI tata
                    if (model.CopieCIT.Length > 0)
                    {
                        string fileNameCIT = Path.GetFileName(model.CopieCIT.FileName);
                        Attachment file2 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCIT, MediaTypeNames.Application.Octet);
                        mm.Attachments.Add(file2);
                        //fie2.Dispose();
                        //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCIT, MediaTypeNames.Application.Octet));
                    }
                    //atasam CI mama
                    if (model.CopieCIM.Length > 0)
                    {
                        string fileNameCIM = Path.GetFileName(model.CopieCIM.FileName);
                        Attachment file3 = new Attachment(model.CopieCN.OpenReadStream(), fileNameCIM, MediaTypeNames.Application.Octet);
                        mm.Attachments.Add(file3);
                        //file3.Dispose();
                        //mm.Attachments.Add(new Attachment(model.CopieCN.OpenReadStream(), fileNameCIM, MediaTypeNames.Application.Octet));
                    }
    
                    //here we try another approach for multi attach
                    //first we create a list of files
                    List<string> AttachList = new List<string>();
                    AttachList.Clear();
                    if (model.CopieCN.Length > 0)
                    {
                        AttachList.Add(Path.GetFileName(model.CopieCN.FileName));
                    }
                    if (model.CopieCIT.Length > 0)
                    {
                        AttachList.Add(Path.GetFileName(model.CopieCIT.FileName));
                    }
                    if (model.CopieCIM.Length > 0)
                    {
                        AttachList.Add(Path.GetFileName(model.CopieCIM.FileName));
                    }
                    //
    
                    foreach (var filepath in AttachList) //this is commented in real life
                    {
                        var attachment = new Attachment(filepath);   // here you can attach a file as a mail attachment  
                        mm.Attachments.Add(attachment);
                    }
                    //
    
                    using (SmtpClient smtp = new SmtpClient())
                    {
                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        NetworkCredential NetworkCred = new NetworkCredential("sender.email@gmail.com", "@Password@");
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = NetworkCred;
                        smtp.Port = 587;
    
                        try {
                            smtp.Send(mm);
                        ViewBag.Message = "Mesaj trimis cu succes."; }
                        catch (Exception ex) {
                            ViewBag.Message = ("S-a produs o eroare: {0}", ex.ToString());
                        }
                        finally
                        {
                            //Clear all the form's fields
                            
                        }
    
    
                }
                }
    
                return View();
                //return new RedirectResult("https://www.some-site.com");
            }
    
    

    Here comes the error:

    /*Error rised*/
    
    /*line 105 is: smtp.Send(mm); */
    
    (S-a produs o eroare: {0}, System.Net.Mail.SmtpException: Failure sending mail. ---> System.InvalidOperationException: The inner stream position has changed unexpectedly. at Microsoft.AspNetCore.Http.ReferenceReadStream.VerifyPosition() at Microsoft.AspNetCore.Http.ReferenceReadStream.Read(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Mime.MimePart.Send(BaseWriter writer, Boolean allowUnicode) at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer, Boolean allowUnicode) at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope, Boolean allowUnicode) at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at Inscrieri.Inima.Controllers.HomeController.Index(EmailModel model) in C:\Users\laurentiu\source\repos\Inscrieri.Inima\Inscrieri.Inima\Controllers\HomeController.cs:line 105)

    Any hint will be appreciated.

    Regards

    Thursday, May 28, 2020 6:14 PM

All replies

  • User-17257777 posted

    Hi net4u,

    Maybe you can try to remove the "using" code block. When you use "using" keywork, internally, Dispose method is invoked. It will make the MemoryStreams be deallocated. 

    For more details, youcan refer to this link.

    Best Regards,

    Jiadong Meng

    Tuesday, June 2, 2020 8:58 AM