Search code examples
c#asp.net-web-api.net-coresmtpmemorystream

Getting Object Reference Not set Error in SMTP mail.send() C#.net core API project while using memory stream


I have a .docx template with some dynamic display strings defined in it like below

 {{FirstName}}, {{ContactNumber}}",{{EmailId}}

Now i need to read this .docx file and need to replace this above texts with its equalent texts and need to send that doc as attachment to the user. This is what i am trying to achieve.

So far i written code like this

 string content = System.IO.File.ReadAllText(path);
 content.Replace("{{FirstName}}", objUser.FirstName);
 content.Replace("{{ContactNumber}}", objUser.Contact);
 content.Replace("{{EmailId}}", objUser.EmailId);

 var stream = new MemoryStream();
 var writer = new StreamWriter(stream);

 writer.WriteLine(content);
 writer.Flush();

 stream.Position = 0;

 using (var client = new SmtpClient())
  {
      client.Host = "relay-hosting.secureserver.net";
      client.Port = 25;

      using (var emailMessage = new MailMessage())
      {
          System.Net.Mime.ContentType contentType = new 
          
  
System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
          var coverAttachment = new Attachment(stream, contentType);
          coverAttachment.ContentDisposition.FileName = "CoverLetter.pdf";
          emailMessage.Attachments.Add(coverAttachment);

         emailMessage.To.Add(new MailAddress(value.toemail));
                            emailMessage.CC.Add(new 
         MailAddress("My To Address"));
         emailMessage.From = new MailAddress(_configuration["Email:Email"]);
         emailMessage.Subject = value.subject;
         emailMessage.Body = message;
         emailMessage.IsBodyHtml = true;
         emailMessage.BodyEncoding = Encoding.UTF8;
         emailMessage.SubjectEncoding = Encoding.Default;
         emailMessage.Priority = MailPriority.High;
         emailMessage.ReplyToList.Add(new MailAddress(_configuration["Email:Email"]));

//And before calling client.send()

i have a code like

client.SendCompleted += (s, e) =>
                            {
                                client.Dispose();
                                emailMessage.Dispose();
                                writer.Dispose();
                            };

Is there is anything i am doing wrong here?


Solution

  • Two observations:

    1. if you have created SmtpClient and MailMessage objects in "using" block, it would automatically call the Dispose methods on these objects. You don't need to call them yourselves.
    2. SendCompleted event occurs when an asynchronous email send operation completes. You should probably use SendAsync() instead of Send()

    More info: https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.sendcompleted?view=net-5.0