278

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 = "user@hotmail.com"; // <-- this one
mail.From = "you@yourcompany.example";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Sam Stephenson
  • 5,200
  • 5
  • 27
  • 44
  • 1
    Nore that if you are trying to send through gmail via SMTP you need to allow less secure apps to access your account https://support.google.com/accounts/answer/6010255?hl=en – Matthew Lock May 06 '17 at 03:48

17 Answers17

365

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

using System.Net.Mail;

...

MailMessage mail = new MailMessage("you@yourcompany.example", "user@hotmail.com");
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);
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
MRB
  • 3,936
  • 1
  • 14
  • 6
  • 9
    mail.To is readonly, from is not. public MailAddressCollection To { get; } – MRB Feb 08 '12 at 21:01
  • 41
    That's because it's a collection. You can just call add to it – Oskar Kjellin Feb 08 '12 at 21:03
  • 17
    @Oskar Okay, so I should have been more specific. You cannot set the mail.to to a specific address. You must use the constructor or call add. I was only addressing the first compiler warning: Error CS0200: Property or indexer 'System.Net.Mail.MailMessage.To' cannot be assigned to -- it is read only – MRB Feb 08 '12 at 21:11
  • If I was going to use this at a work and wanted to use something other than google what would I set the host to. I have looked in outlook and I have something like this somevaluehere.wy.local can this be done from an email service that requires a password our on an outlook.com email software? – Doug Hauf Dec 20 '13 at 19:02
  • 9
    @DougHauf You can use the SmtpClient class with a password protected smtp server. your smtp server seems to be an internal server which would mean that your program will only be able to connect to that smtp server when it's on the network. `client.Host = "mail.youroutgoingsmtpserver.com";` `client.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");` – clifford.duke Dec 23 '13 at 02:04
  • I do get an exception at client.Send(mail) saying that an exception occured in in System.dll "System.Net.Mail.SmtpException" What should I do ? – CMS May 30 '14 at 13:20
  • 2
    What are your `using`s? – Cullub Jul 11 '14 at 14:26
  • 4
    SmtpClient implements IDisposable, so you should probably change it to: using (SmtpClient client = new SmtpClient()) { ... } – Mark Miller Apr 10 '15 at 19:11
  • 3
    Do take into account that `smtp.gmail.com` only accepts SSL traffic. So use port `587` (TLS) or `465` (SSL). – DdW Jun 23 '16 at 07:32
  • 3
    btw, the smtp server has changed to "smtp.gmail.com" – Andrew Chaa Dec 16 '16 at 15:49
  • Use `aspmx.l.google.com` for restricted Gmail SMTP server, for non-TLS and only gmail https://support.google.com/a/answer/176600?hl=en – Hrvoje T Nov 14 '18 at 09:02
  • [`MailMessage`](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage) also implements `IDisposable`, so it should be wrapped in a `using` block. – Lews Therin Jan 22 '19 at 15:49
  • 1
    @Cullub C# SMTP requires `using System.Net.Mail;` – TylerH Jun 07 '19 at 17:37
  • How to implement this inside an echo bot on azure? – sanjana jha May 20 '20 at 11:00
261

This :

mail.To = "user@hotmail.com";

Should be:

mail.To.Add(new MailAddress("user@hotmail.com"));
Mithrandir
  • 24,869
  • 6
  • 50
  • 66
  • Using this and the default `MailMessage` constructor allows you to set the `To` field without setting the `From`, which will default to the value in the [ Element (Network Settings)](https://msdn.microsoft.com/en-us/library/ms164240(v=vs.110).aspx) – bstoney Oct 10 '16 at 22:01
  • Can anybody tell me how can I make this working for my own SMTP server instead of Google SMTP? I am receiving `{"Unable to connect to the remote server"} {"The requested address is not valid in its context IP-ADDRESS:25"}`error when I'm trying to connect to my SMTP server – YuDroid Dec 28 '16 at 10:16
  • @YuDroid Set the `Host` and `Port` properties of the `SmtpClient`correctly. – Mithrandir Dec 28 '16 at 15:13
  • @Mithrandir Yes I'm setting it correctly. I have setup my SMTP mail account in Outlook and grabbed all necessary settings from their. Host and Port are declared in Web.config file and I'm fetching it runtime. – YuDroid Jan 02 '17 at 12:08
121

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("user@gmail.com","password");

MailMessage mm = new MailMessage("donotreply@domain.example", "sendtomyemail@domain.example", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

sorry about poor spelling before

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Sam Stephenson
  • 5,200
  • 5
  • 27
  • 44
19
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("myemail@gmail.com", "password");
    client.Send(Message); 
}
Mo Patel
  • 2,321
  • 4
  • 22
  • 37
Mnyikka
  • 1,223
  • 17
  • 12
  • 4
    This doesn't at all address why the OP's assignment to `MailMessage` properties can't be done. – ProfK Nov 09 '14 at 12:13
17

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("from@server.com");
objeto_mail.To.Add(new MailAddress("to@server.com"));
objeto_mail.Subject = "Password Recover";
objeto_mail.Body = "Message";
client.Send(objeto_mail);
BJury
  • 2,526
  • 3
  • 16
  • 27
user2332898
  • 171
  • 1
  • 3
13

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("from@gmail.com", "to1@gmail.com", "Hello", mailBodyhtml);
        msg.To.Add("to2@gmail.com");
        msg.IsBodyHtml = true;
        var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "from@hotmail.com" then host should be "smtp.hotmail.com"**
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new NetworkCredential("from@gmail.com", "password");
        smtpClient.EnableSsl = true;
        smtpClient.Send(msg);
        Console.WriteLine("Email Sent Successfully");
    }
Community
  • 1
  • 1
Siddarth Kanted
  • 5,738
  • 1
  • 29
  • 20
7

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

Haider Ali Wajihi
  • 2,756
  • 7
  • 51
  • 82
DoodleKana
  • 2,106
  • 4
  • 27
  • 45
4

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);
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Doug Null
  • 7,989
  • 15
  • 69
  • 148
3

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; }
}
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
2
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

Tshilidzi Mudau
  • 7,373
  • 6
  • 36
  • 49
jishan siddique
  • 1,848
  • 2
  • 12
  • 23
  • While this video may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes – afxentios Jan 31 '17 at 10:55
  • [msdn](https://msdn.microsoft.com/en-us//library/system.net.mail.smtpclient.usedefaultcredentials(v=vs.110).aspx) stated for the UseDefaultCredentials property that _"If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server."_, therefore you shall set the UseDefaultCredentials property to false if you had used the Credentials property (custom credentials). – Sergei Iashin Mar 17 '17 at 20:28
1
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

Mo Patel
  • 2,321
  • 4
  • 22
  • 37
somesh
  • 3,508
  • 4
  • 16
  • 10
1

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);
}
Ahmed El-Hansy
  • 160
  • 1
  • 15
1

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, sender@address.com));
            mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
            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("user@name.com", "password");

                    smtpClient.Send(mailMessage);
                    Console.WriteLine("Success");
                }
            }
            catch (SmtpCommandException ex)
            {
                Console.WriteLine(ex.ToString());              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());                
            }
Naveen
  • 1,441
  • 2
  • 16
  • 41
0

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

string from = "codeforwin@gmail.com";  //Senders email   
string to = "reciever@gmail.com";  //Receiver's email  
MailMessage msg = new MailMessage(from, to); 

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

Pankaj Prakash
  • 2,300
  • 30
  • 31
0

this would work too..

string your_id = "your_id@gmail.com";
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, "recepient@gmail.com", "subject", "body");
   client.Send(mm);
   Console.WriteLine("Email Sent");
 }
 catch (Exception e)
 {
   Console.WriteLine("Could not end email\n\n"+e.ToString());
 }
user3188978
  • 119
  • 2
  • 15
0
 //Hope you find it useful, it contain too many things

    string smtpAddress = "smtp.xyz.com";
    int portNumber = 587;
    bool enableSSL = true;
    string m_userName = "support@xyz.com";
    string m_UserpassWord = "56436578";

    public void SendEmail(Customer _customers)
    {
        string emailID = gghdgfh@gmail.com;
        string userName = DemoUser;

        string emailFrom = "qwerty@gmail.com";
        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);
            }
        }
    }
Dutt93
  • 118
  • 10
  • 2
    Please consider using your answer to explain the solution and why the original asker was running into an issue instead of simply posting a wall of code. This will be more useful both for the original asker and future visitors to understand why the issue occurred in the first place. – RedBassett Feb 06 '17 at 10:25
  • @RedBassett Thanks for the suggestion. I just edited and put some information in comments, next time I keep in mind whatever the things you told. – Dutt93 Feb 06 '17 at 11:17
0

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);
        }
    }
Morteza Sefidi
  • 105
  • 1
  • 4