0
votes

I'm trying to create a code prototype that can send e-mail to my gmail by referring SMTPClient - msdn with winforms

protected void sendMail()
    {



        MailAddress from = new MailAddress("[email protected]", "Sender", System.Text.Encoding.UTF8);
        MailAddress to = new MailAddress("[email protected]");
        MailMessage message = new MailMessage(from, to);


        message.Body = "This is a test e-mail message sent by an application. ";
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.Subject = "test message 1";
        message.SubjectEncoding = System.Text.Encoding.UTF8;

        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
        string userState = "test message1";
        client.SendAsync(message, userState);
        message.Dispose();
    }

private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        String token = (string)e.UserState;

        if (e.Cancelled)
        {
            MessageBox.Show("send cancelled", "Mail status");
        }
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.ToString(), "Mail status");
        }
        else
        {
            MessageBox.Show("Message sent", "Mail status");
        }
        mailSent = true;
    }

the app.config looks like this:

<configuration>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.net>
    <mailSettings>
        <smtp from="[email protected]">
            <network host="smtp.gmail.com" userName="[email protected]" password="app_specific_password" port="467" defaultCredentials="false"/>
        </smtp>
    </mailSettings>
</system.net>
</configuration>

but when i run the app, it seems that it does not take the credentials from the configuration file.

The exception received states that:

System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server >> ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond >> after a period of time or established connection failed because connected host has failed to respond 74.125.24.108:467 at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) --- End of inner exception stack trace --- at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult result) at System.Net.Mail.SmtpTransport.EndGetConnection(IAsyncResult result) at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result) --- End of inner exception stack trace ---

P.S.: I have searched and tried to hardcode directly into the code which actually worked but I'm very specific in using app.config instead of those ways

Edit: Please make a note, I've recently added two lines of code as I missed them while posting. But still it doesn't work

3
When debugging, what there is in the variables that should contain what is read from the configuration?Liquid Core
@LiquidCore there are values which I have mentioned in the app.config, but still the exception is being thrown.Loves2Code
Your title implies that it's being caused by the lack of credentials. However, the error message states that it's a connectivity problem (i.e. the server is not responding, or offline, or the network is down, or you are using an invalid server name). If the wrong credentials were being used, you'd get a different error message.Flater
@Flater thank you, yes I will modify the question now but its a gmail smtp server... even my side network is working... the exception is quite confusingLoves2Code
The port number is wrong, gmail servers use 465.Hans Passant

3 Answers

0
votes

You reference to SMTPClient - msdn but in this example function have args[]. How you are giving login and password to your function?

About port: i used port 587 once.

0
votes

Try this:

Note Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

Whatch out for the port being 587 or 465, check what is the one you need.

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

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}
0
votes

Thank you guys, for making attempts to help me. I got it resolved by removing these lines from the code:

    client.EnableSsl = true;
    client.UseDefaultCredentials = false;

and changed the <network/> in app.config as follows

<network host="smtp.gmail.com" userName="[email protected]" password="app_specific_password" port="587" enableSsl="true"/>

Then, it worked