0

Is it possible to address a mailmessage to a 'name' instead of an 'e-mailaddress'.

Something like this:

MailMessage mmsg = new MailMessage();
mmsg.To.Add("Winfrey");

instead of:

MailMessage mmsg = new MailMessage();
mmsg.To.Add(new MailAddress("Winfrey@user.com"));

Is it possible to add something in the 'To' part without the '@' and domain? And if so, how?

xtra
  • 1,957
  • 4
  • 22
  • 40
  • 1
    It's an email messaging api. Everything will have to be an email address. – interesting-name-here Jan 08 '18 at 15:06
  • 1
    No, the mail classes don't have an internal address book. –  Jan 08 '18 at 15:06
  • What would you expect the SmtpClient to do with an address that isn't an address? No, you can't. – peeebeee Jan 08 '18 at 15:07
  • @Adola That has nothing to do with C#. It is just the implementation of MailMessage and MailAddress class – Sir Rufo Jan 08 '18 at 15:08
  • What is your expectation? From where it should look up the real email (with @domain.com)? – Sunil Jan 08 '18 at 15:09
  • If you want to use outlook interop, that may be different but I haven't looked too much into that. https://stackoverflow.com/questions/11223462/how-to-send-a-mail-using-microsoft-office-interop-outlook-mailitem-by-specifying . I would assume you could query the contact list and grab people by their name with that. There are probably other APIs that do this as well for whatever email client the user may have. `MailMessage` does not though. – interesting-name-here Jan 08 '18 at 15:09
  • You could write your own logic that looks up email addresses based on names. Of course, that's awfully risky, what if two people have the same name? Or someone has a name change? You really should have an ID assigned to each user and then you can look email addresses up based on the ID. – mason Jan 08 '18 at 15:12
  • Purpose was that another tool could read the number in the "To" box and find a mailaddress based on this number in a database. – xtra Jan 08 '18 at 21:46
  • @xtra That sounds like an external address book to me. See my answer below – Mark Jan 09 '18 at 06:09

3 Answers3

4

The MailMessage class does not provide this. From where should this class know, which mail address is behind 'Winfrey'?
The only way is to create a simple address book.

Then you can write this

mmsg.To.Add(_addressBook["Winfrey"]);

_addressBook is a Dictionary here.

Dictionary<string, string> _addressBook = new Dictionary<string,string>();



Does this help?

Mark
  • 307
  • 2
  • 12
1

If you are looking to see the sender's name on the e-mail that the other user receives:

MailMessage mail = new MailMessage();
mail.From = new MailAddress("winfrey@user.com", "winfrey" );

It'll display the name Winfrey.

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
1

System.Net.Mail doesn't validate the email that you are sending to. MailMessage.To only accepts email address. See this!

Adola
  • 337
  • 1
  • 16