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

C#EmailSmtpclient

C# Problem Overview


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 = new SmtpClient();            
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.To = "[email protected]"; // <-- this one
mail.From = "[email protected]";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

C# Solutions


Solution 1 - C#

mail.To and mail.From are readonly. Move them to the constructor.

using System.Net.Mail;

...

MailMessage mail = new MailMessage("[email protected]", "[email protected]");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

Solution 2 - C#

This :

mail.To = "[email protected]";

Should be:

mail.To.Add(new MailAddress("[email protected]"));

Solution 3 - C#

Finally got working :)

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

...

// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

sorry about poor spelling before

Solution 4 - C#

public static void SendMail(MailMessage Message)
{
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.googlemail.com";
    client.Port = 587;
    client.UseDefaultCredentials = false;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential("[email protected]", "password");
    client.Send(Message); 
}

Solution 5 - C#

This is how it works for me. Hope you find it useful

MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "smtp.internal.mycompany.com";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user", "Password");
objeto_mail.From = new MailAddress("[email protected]");
objeto_mail.To.Add(new MailAddress("[email protected]"));
objeto_mail.Subject = "Password Recover";
objeto_mail.Body = "Message";
client.Send(objeto_mail);

Solution 6 - C#

First go to https://myaccount.google.com/lesssecureapps and make Allow less secure apps true.

Then use the below code. This below code will work only if your from email address is from gmail.

static void SendEmail()
    {
        string mailBodyhtml =
            "<p>some text here</p>";
        var msg = new MailMessage("[email protected]", "[email protected]", "Hello", mailBodyhtml);
        msg.To.Add("[email protected]");
        msg.IsBodyHtml = true;
        var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "[email protected]" then host should be "smtp.hotmail.com"**
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new NetworkCredential("[email protected]", "password");
        smtpClient.EnableSsl = true;
        smtpClient.Send(msg);
        Console.WriteLine("Email Sent Successfully");
    }

Solution 7 - C#

If you want to have your email and password not appear in your code and want your company email client server to use your windows credentials use below.

client.Credentials = CredentialCache.DefaultNetworkCredentials;

Source

Solution 8 - C#

This just worked for me as of March 2017. Started with solution from above "Finally got working :)" which didn't work at first.

SmtpClient client = new SmtpClient();
client.Port =  587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("<me>@gmail.com", "<my pw>");
MailMessage mm = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

Solution 9 - C#

This answer features:

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; }
}

Solution 10 - C#

MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
	string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
	mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");
    

View Video: https://www.youtube.com/watch?v=bUUNv-19QAI

Solution 11 - C#

smtp.Host = "smtp.gmail.com"; // the host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;

Go through this article for more details

Solution 12 - C#

Just need to try this:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
   smtp.Credentials = new NetworkCredential(emailFrom, password);
   smtp.EnableSsl = enableSSL;
   smtp.Send(mail);
}

Solution 13 - C#

MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices. It has more and advance features better than System.Net.Mail Microsoft TNEF support via MimeKit.

Download nuget package from here.

See this example you can send mail

            MimeMessage mailMessage = new MimeMessage();
            mailMessage.From.Add(new MailboxAddress(senderName, [email protected]));
            mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
            mailMessage.To.Add(new MailboxAddress(emailid, emailid));
            mailMessage.Subject = subject;
            mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
            mailMessage.Subject = subject;
            var builder = new BodyBuilder();
            builder.TextBody = "Hello There";            
            try
            {
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                    smtpClient.Authenticate("[email protected]", "password");

                    smtpClient.Send(mailMessage);
                    Console.WriteLine("Success");
                }
            }
            catch (SmtpCommandException ex)
            {
                Console.WriteLine(ex.ToString());              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());                
            }

Solution 14 - C#

Initialize the MailMessage with sender and reciever's email addresses. It should be something like

string from = "[email protected]";  //Senders email   
string to = "[email protected]";  //Receiver's email  
MailMessage msg = new MailMessage(from, to); 

Read the full code snippet of how to send emails in c#

Solution 15 - C#

this would work too..

string your_id = "[email protected]";
string your_password = "password";
try
{
   SmtpClient client = new SmtpClient
   {
     Host = "smtp.gmail.com",
     Port = 587,
     EnableSsl = true,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     Credentials = new System.Net.NetworkCredential(your_id, your_password),
     Timeout = 10000,
   };
   MailMessage mm = new MailMessage(your_iD, "[email protected]", "subject", "body");
   client.Send(mm);
   Console.WriteLine("Email Sent");
 }
 catch (Exception e)
 {
   Console.WriteLine("Could not end email\n\n"+e.ToString());
 }

Solution 16 - C#

 //Hope you find it useful, it contain too many things

    string smtpAddress = "smtp.xyz.com";
    int portNumber = 587;
    bool enableSSL = true;
    string m_userName = "[email protected]";
    string m_UserpassWord = "56436578";
    
    public void SendEmail(Customer _customers)
    {
        string emailID = [email protected];
        string userName = DemoUser;

        string emailFrom = "[email protected]";
        string password = "qwerty";
        string emailTo = emailID;

        // Here you can put subject of the mail
        string subject = "Registration";
        // Body of the mail
        string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
        body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
        body += "<br />";
        body += "Dear " + userName + ",";
        body += "<br />";
        body += "<p>";
        body += "Thank you for registering </p>";            
        body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
        body += " <br />";
        body += "Thanks,";
        body += "<br />";
        body += "<b>The Team</b>";
        body += "</div>";
       // this is done using  using System.Net.Mail; & using System.Net; 
        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(emailTo);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            // Can set to false, if you are sending pure text.
            
            using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            {
                smtp.Credentials = new NetworkCredential(emailFrom, password);
                smtp.EnableSsl = enableSSL;
                smtp.Send(mail);
            }
        }
    }

Solution 17 - C#

send email by smtp

public void EmailSend(string subject, string host, string from, string to, string body, int port, string username, string password, bool enableSsl)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtpServer = new SmtpClient(host);
            mail.Subject = subject;
            mail.From = new MailAddress(from);
            mail.To.Add(to);
            mail.Body = body;
            smtpServer.Port = port;
            smtpServer.Credentials = new NetworkCredential(username, password);
            smtpServer.EnableSsl = enableSsl;
            smtpServer.Send(mail);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSam StephensonView Question on Stackoverflow
Solution 1 - C#MRBView Answer on Stackoverflow
Solution 2 - C#MithrandirView Answer on Stackoverflow
Solution 3 - C#Sam StephensonView Answer on Stackoverflow
Solution 4 - C#MnyikkaView Answer on Stackoverflow
Solution 5 - C#user2332898View Answer on Stackoverflow
Solution 6 - C#Siddarth KantedView Answer on Stackoverflow
Solution 7 - C#DoodleKanaView Answer on Stackoverflow
Solution 8 - C#Doug NullView Answer on Stackoverflow
Solution 9 - C#Fabian BiglerView Answer on Stackoverflow
Solution 10 - C#jishan siddiqueView Answer on Stackoverflow
Solution 11 - C#someshView Answer on Stackoverflow
Solution 12 - C#Ahmed El-HansyView Answer on Stackoverflow
Solution 13 - C#NaveenView Answer on Stackoverflow
Solution 14 - C#Pankaj PrakashView Answer on Stackoverflow
Solution 15 - C#user3188978View Answer on Stackoverflow
Solution 16 - C#Dutt93View Answer on Stackoverflow
Solution 17 - C#Morteza SefidiView Answer on Stackoverflow