CodeWalker
CodeWalker

Reputation: 2388

Strings not compatible for email address

I am new to C#. In my verge of learning this language, I made a windows form application application that takes in an email address and a password and sends it to a pre-specified email address. I don't think that I have messed up the data types though I am getting an error The specified string is not in the form required for an e-mail address.

My code is below :

namespace mailTest
{


public partial class Form1 : Form
{
    string mailAddress = "[email protected]";
    string mailPassword = "123456789";
    string SMTP = "smtp.gmail.com";

    public Form1()
    {
        InitializeComponent();
    }


    private void button_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage(Email.Text, Password.Text); \\ I get the error on this line
        SmtpClient client = new SmtpClient(SMTP);
        client.Port = 587;
        client.Credentials = new System.Net.NetworkCredential(mailAddress,mailPassword);
        client.EnableSsl = true;
        client.Send(mail);
        MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);
    }
}
}

Screenshot of my form :

enter image description here

Upvotes: 0

Views: 140

Answers (3)

Alexander Bell
Alexander Bell

Reputation: 7918

You have to specify UserName in NetworkCredential , like the following:

NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = passwd;

See the explanation at: http://msdn.microsoft.com/en-us/library/system.net.networkcredential.username%28v=vs.110%29.aspx

Also, your MailMessage has wrong parameters (shoud be from/to). Regards,

Upvotes: 1

Ian Nelson
Ian Nelson

Reputation: 58753

That particular constructor of the MailMessage class expects the first parameter to be the email address of the sender, and the second parameter to be the email address of the recipient:

http://msdn.microsoft.com/en-us/library/14k9fb7t(v=vs.110).aspx

You are providing a password to the parameter that expects the recipient's email address.

I presume you really want to pass the password in the body of the message.

Take a look at the constructor that populates the body, or set the Body property after initializing a MailMessage:

http://msdn.microsoft.com/en-us/library/5k0ddab0(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.body(v=vs.110).aspx

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

MailMessage constructor is defined as below

public MailMessage(string from, string to);

First parameter is from address and second is to address, but you seem to pass password in second parameter. That's why you get the exception.

Upvotes: 6

Related Questions