douji1999 2016-11-21 04:27
浏览 57
已采纳

MailMessage是否需要任何设置来初始化?

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?

  • 写回答

3条回答 默认 最新

  • dszsajhd237437 2016-11-21 04:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置