1

I would like some help with my coding please. I am trying to send an message to an email but I keep getting an error after I try to click on the button and send the message. Below is the coding:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;


namespace CO6009DissertationV5
{

    public partial class frmSendMsg : Form
    {

        public frmSendMsg()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;

            System.Net.NetworkCredential userpassword = new System.Net.NetworkCredential();
            userpassword.UserName = "user@gmail.com";
            userpassword.Password = "password";

            client.Credentials = userpassword;

            MailMessage msg = new MailMessage("user@gmail.com", "user@gmail.com");
            **msg.To.Add(new MailAddress(txtBoxToEmail.Text));**
            msg.Body = "<b> Sender's Name: </b>" + txtBoxName.Text + "<p><b> Sender's E-mail: </b>" + txtBoxEmail.Text + "<p><b>Sender's Subject: </b>" + txtBoxSubject.Text + "<p><b>Sender's Message: </b>" + "<p>" + txtBoxMsg.Text;
            msg.Subject = txtBoxSubject.Text;
            msg.IsBodyHtml = true;

            try
            {
                client.Send(msg);
                lblMsgStatus.Text = "<p> Message Successfully Sent </p>";
            }

            catch (Exception ex)
            {
                lblMsgStatus.Text = "Send failed";
            }
        }
    }
}

The main problem seems to be this line:

msg.To.Add(new MailAddress(txtBoxToEmail.Text));

As the project keeps stopping here, giving the error line:

{"The parameter 'addresses' cannot be an empty string.\r\nParameter name: addresses"}.

Any help would be appreciated.

Pikoh
  • 7,582
  • 28
  • 53
AdrianAndrews
  • 33
  • 1
  • 6
  • 2
    Never paste code with your user/password here! – Pikoh Jan 24 '17 at 08:16
  • 1
    Could you please add the text of the error message you get? – Filburt Jan 24 '17 at 08:16
  • Also check [Sending email in .NET through Gmail](http://stackoverflow.com/q/32260/205233) and many other question already asked - it is very likely that someone encountered your error before. – Filburt Jan 24 '17 at 08:19
  • That error is self explanatory. It seems you are adding an empty mail... – Pikoh Jan 24 '17 at 08:26
  • The error is clear - the textbox is empty. Check the textbox contents *before* sending the message, eg with `String.IsNullOrWhitespace`. Better yet, use Windows Forms validation to prevent the user from sending with an empty address box. Check [User Input Validation in Windows Forms](https://msdn.microsoft.com/en-us/library/ms229603(v=vs.110).aspx). – Panagiotis Kanavos Feb 06 '17 at 08:58

4 Answers4

2

This line can fail only if txtBoxToEmail.Text is not a valid e-mail address

msg.To.Add(new MailAddress(txtBoxToEmail.Text));

If it's still not clear, please wrap your code with try-catch and evaluate exception details

EDIT: I see your edit, i think the exception message "The parameter 'addresses' cannot be an empty string.\r\nParameter name: addresses" is pretty clear

user3175253
  • 588
  • 4
  • 10
2

The error message is pretty clear - the TO address text is empty. This means that txtBoxToEmail.Text is empty.

You can avoid such problems in the future by checking the address before using it. You can easily check for empty strings with String.IsNullOrWhitespace, eg:

private void btnSend_Click(object sender, EventArgs e)
{
    if (String.IsNullOrWhitespace(txtBoxToEmail.Text))
    {
        MessageBox.Show("To can't be empty!","Invalid Address",
                        MessageBoxButtons.OK,MessageBoxIcon.Error);
        return;
    }
...

You can add more elaborate checks, eg ensuring that the text contains a @ character.

An even better solution though, would be to add validation to the controls and form itself, so that the user can't try to send an email without typing the correct input.

Windows Forms provides many ways to validate input, as described in User Input Validation in Windows Forms.

You can handle the Validating event of txtBoxToEmail to check for a valid address and prevent the user from leaving the control until the address is correct. In fact, the documentation's example is an email validation! :

private void textBox1_Validating(object sender, 
                System.ComponentModel.CancelEventArgs e)
{
   string errorMsg;
   if(!ValidEmailAddress(textBox1.Text, out errorMsg))
   {
      // Cancel the event and select the text to be corrected by the user.
      e.Cancel = true;
      textBox1.Select(0, textBox1.Text.Length);

      // Set the ErrorProvider error with the text to display. 
      this.errorProvider1.SetError(textBox1, errorMsg);
   }
}

private void textBox1_Validated(object sender, System.EventArgs e)
{
   // If all conditions have been met, clear the ErrorProvider of errors.
   errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
   // Confirm that the e-mail address string is not empty.
   if(String.IsNullOrWhitespace(emailAddress.Length))
   {
      errorMessage = "e-mail address is required.";
         return false;
   }

   // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
   if(emailAddress.IndexOf("@") > -1)
   {
      if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
      {
         errorMessage = "";
         return true;
      }
   }

   errorMessage = "e-mail address must be valid e-mail address format.\n" +
      "For example 'someone@example.com' ";
      return false;
}

The sample uses the ErrorProvider component to display an exclamation mark and error UI next to the offending input.

You can find more information about ErrorProvider in How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
1

Its better to validate your EmailId before send mail. Kindly add below method and call it in your button click event like this :

     if (IsValidEmail(txtBoxToEmail.Text))
     {
            msg.To.Add(new MailAddress(txtBoxToEmail.Text));
     } 

Method to validate Email id :

    static bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }
Karthikeyan
  • 333
  • 5
  • 17
  • This is the same thing as the original code, wrapped in a try/catch. This doesn't perform any kind of validation. The OP has *already* wrapped the code in a `try/catch` block. – Panagiotis Kanavos Feb 06 '17 at 08:55
  • @ Panagiotis Kanavos Could u tell the null check in Original Code? – Karthikeyan Feb 06 '17 at 09:04
  • @ Panagiotis Kanavos The answer that i posted will check null. – Karthikeyan Feb 06 '17 at 09:05
  • I already explained it. This is the same code as that used by the OP. It doesn't solve the problem. The OP *already* receives an exception and already produces a message. Validation means actually checking to see that the value is OK – Panagiotis Kanavos Feb 06 '17 at 09:16
  • Panagiotis Kanavo : fine. Could u tell me where u find null check of email id in the original code? . The above code that i posted will check null. It may be the good solution. If still u think this solution is down voted. Thanks. I try to give some better solution in feature. – Karthikeyan Feb 06 '17 at 09:20
  • Your code doesn't check anything at all. It does the exact same thing as the original code `new MailAddress(txtBoxToEmail.Text)`. If that throws, just like the original code, you catch it. In fact, *this* code loses the error message and returns an ambiguous `true/false` result. Why did the address fail? No idea – Panagiotis Kanavos Feb 06 '17 at 09:35
  • Check the example for the [Control.Validating](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx) event to see how validating an email should work. – Panagiotis Kanavos Feb 06 '17 at 09:36
  • I'll also copy your comment from another answer: Do some research first. I started looking for plagiarism and found a lot of dangerous answers, like opening connections without `using` or forgetting to close them. Be careful before you post, you can cause some real damage – Panagiotis Kanavos Feb 06 '17 at 09:40
  • Okie. i take care. – Karthikeyan Feb 06 '17 at 09:43
1

The good way is checking the value of txtBoxToEmail.Text. maybe it is null or empty. Then use .To.Add(new MailAddress(txtBoxToEmail.Text));

xici
  • 81
  • 1