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("papuccino1@gmail.com", "password"),
EnableSsl = true
};
client.Send("papuccino1@gmail.com", "stapia.gutierrez@gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
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).