Why do I get “'property cannot be assigned” when sending an SMTP email?

前端 未结 17 2253
醉话见心
醉话见心 2020-11-22 05:50

I can\'t understand why this code is not working. I get an error saying property can not be assigned

MailMessage mail = new MailMessage();
SmtpClient client          


        
17条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:42

    This answer features:

    • Using 'using' whenever possible (IDisposable interfaces)
    • Using Object initializers
    • Async Programming
    • Extract SmtpConfig to external class (adjust it to your needs)

    Here's the extracted code:

        public async Task SendAsync(string subject, string body, string to)
        {
            using (var message = new MailMessage(smtpConfig.FromAddress, to)
            {
                Subject = subject,
                Body = body,
                IsBodyHtml = true
            })
            {
                using (var client = new SmtpClient()
                {
                    Port = smtpConfig.Port,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Host = smtpConfig.Host,
                    Credentials = new NetworkCredential(smtpConfig.User, smtpConfig.Password),
                })
                {
                    await client.SendMailAsync(message);
                }
            }                                     
        }
    

    Class SmtpConfig:

    public class SmtpConfig
    {
        public string Host { get; set; }
        public string User { get; set; }
        public string Password { get; set; }
        public int Port { get; set; }
        public string FromAddress { get; set; }
    }
    

提交回复
热议问题