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