tags:

views:

38

answers:

2

Using this code, I can send emails to people. However, every time I press the send button, I think I log back in, correct?

Is there a way to perpetuate my login session, or is the way it's always been done ("I'm making a newbie assumption")?

        var client = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new NetworkCredential("[email protected]", "password"),
            EnableSsl = true
        };
        client.Send("[email protected]", "[email protected]", "test", "testbody");
        Console.WriteLine("Sent");
        Console.ReadLine();
+1  A: 

Each SMTP session starts with authentication usually. As far as I know there is no way to keep a session open to a SMTP server. It is possble to send a number of emails in a batch though, this is probably what happens when you use an email client.

edosoft
+3  A: 

The code you have is fine. Yes, the smtp service is sending the credentials to the smtp server each time you send the email.

From a coding perspective, this is the preferred way of doing things. If you are batching emails, then you would simply put the .Send method call inside the loop while the new SmtpClient call is above it.

You only want to leave the connection open long enough to do the job then you close it. Otherwise you run the risk of the app blowing up or otherwise failing to close the connection later. Servers only have a limited number of connections that they can handle. If most apps left them open for long periods of time then other users would have a hard time getting in.

Most mail clients, open the connection, send any emails in the outbox, grab any new emails, then close the connection. When a timer goes off, it will do the process over again.

Outlook tied to Exchange works slightly differently because there is a push component (from the server).

Chris Lively
Thanks, this answer was very informative and when I read it, sounds logical to open a connection every time. Thanks again. :D
Sergio Tapia