Sending email through Gmail SMTP server with C#

CVertex picture CVertex · Apr 1, 2009 · Viewed 467.1k times · Source

For some reason neither the accepted answer nor any others work for me for "Sending email in .NET through Gmail". Why would they not work?

UPDATE: I have tried all the answers (accepted and otherwise) in the other question, but none of them work.

I would just like to know if it works for anyone else, otherwise Google may have changed something (which has happened before).

When I try the piece of code that uses SmtpDeliveryMethod.Network, I quickly receive an SmtpException on Send(message). The message is

The SMTP server requires a secure connection or the client was not authenticated.

The server response was:

5.5.1 Authentication Required. Learn more at" <-- seriously, it ends there.

UPDATE:

This is a question that I asked a long time ago, and the accepted answer is code that I've used many, many times on different projects.

I've taken some of the ideas in this post and other EmailSender projects to create an EmailSender project at Codeplex. It's designed for testability and supports my favourite SMTP services such as GoDaddy and Gmail.

Answer

eglasius picture eglasius · Apr 2, 2009

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("[email protected]", "mypwd"),
                EnableSsl = true
            };
            client.Send("[email protected]", "[email protected]", "test", "testbody");
            Console.WriteLine("Sent");
            Console.ReadLine();
        }
    }
}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).