MRfuxkYou MRfuxkYou - 17 days ago 6
PHP Question

does the MailMessage require any setting to initialize?

In my console program, I want to send email to someone by using

System.Net.Mail.MailMessage
. However, I cannot initialize it :(

namespace:

using System.Net;
using System.Net.Mail;


code:

class emailHelper
{
string to = "jane@address.com";
string from = "ben@address.com";
MailMessage message = new MailMessage(from, to);// errors here
}


the error message is about :


A field initializer cannot reference the non-static field, method, or
property 'programA.emailHelper.from'

A field initializer cannot reference the non-static field, method, or
property 'programA.emailHelper.to'


I have no idea that do I miss something to set before using MailMessage.

Any idea?

Answer

The error message give you all the information.

A field initializer cannot reference the non-static field, method, or property

So if you want to make it work, you should make your string fields static. Which I doubt is what you want.

class emailHelper
{
    static string to = "jane@address.com";
    static string from = "ben@address.com";
    MailMessage message = new MailMessage(from, to);// errors here
}

Like I said this is not what you want from one helper method, to have static to and from address. Your code should look like this:

public class EmailHelper
{
    public string To {get; set;}
    public string From {get; set;}
    public MailMessage message {get; set;}

    public EmailHelper(string to, string from)
    {
         To = to;
         From = from;

         message = new MailMessage(from, to);
    }

}

In this case you have addresses which are coming out of the helper and you can create multiple MailMessage classes.