Search code examples
c#.nettype-conversionsystem.net.mail

Cannot implicitly convert to type string to System.Net.Mail.MailAddress


I am working on an inventory application system that is updating tracking forms, and I recently converted from System.Web.Mail to System.Net.Mail.

However in regards to an exception if-else statement I made that handles when an item transfer fails, I get a:

Cannot implicitly convert type 'string' to 'System.Net.Mail.MailAddressCollection"

error for the following code block:

else //If the Item Transfer Fails
{
   _formToUpdate.WorkFlowStep = "d";
   _formToUpdate.InventoryCertifier_Initials = dbcontext.Custodies.Where(x => x.Custody_eraider == User.Identity.Name.ToLower()
   _formToUpdate.InventoryCertifierInitials_DtTm = DateTime.Now;
   _formToUpdate.IsFormLockedforEditing = true;

//The notification lists are different in both cases.
NotificationEmail.To = dbcontext.Custodies.Where(x => x.Custody_eraider ==
_formToUpdate.TransferFrom_Sign).Single().Custody_Email + ","
 + dbcontext.Custodies.Where(x => x.Custody_eraider == _formToUpdate.TransferTo_Sign).
Single().Custody_Email + "," + dbcontext.Custodies.Where(x => x.Custody_eraider ==
_formToUpdate.Form_Approv_Reject_By).Single().Custody_Email + ","
+ dbContext.Custodies.Where(x => x.Custody_eraider == _formToUpdate.InventoryCertifier_
Initials).Single().Custody_Email;
}

The error just occurs in the portion of the code that starts with NotificationEmail.To = ...

I'm just not too sure how to go about revising that statement properly.


Solution

  • The error is telling you that you cannot convert a string to a MailAddressCollection.

    In the System.Net.Mail.MailMessage class, the To property is a MailAddressCollection, not a string as it was in System.Web.Mail.MailMessage.

    You'll need to add the email address(es) to that collection. The MailAddressCollection has an Add method that looks like it takes a string in the same format as before, so your code should probably look like:

    NotificationEmail.To.Add(/* your expression here */);