July 23, 2024


Forever Driven Computer

C# – Sending SMTP Email

C# – Sending SMTP Email

C# can send emails with the .NET Framework fairly easily, especially via the SMTP protocol. The SMTP protocol is a common way to send emails.

Because SMTP emails require an SMTP server to send, it is probably easiest to use Google’s Gmail server. Thus you’ll need a Gmail account, which is simple and free to create. Once you have a Gmail account sending SMTP emails with C# is a breeze. The trick is to use the System.Net.Mail namespace instead of System.Web.Mail. The second namespace was replaced by System.Net starting on .NET Framework 2.0.

But what do you do to connect to Google’s server? You need a few bits of information. The first is that Gmail’s SMTP server address is smtp.gmail.com. The second thing you need to know is that the C# application must connect through port 587. How do we know this? The information is provided to developers freely by Google. Other SMTP servers also provide their own address and port to connect with.

However there is still one more thing, most SMTP servers need authentication to send your emails. This is where the Gmail account comes into play. Using the NetworkCredential .NET class, specify your username and password. This will authenticate your connection with the server. Just make sure your username includes @gmail.com.

Everything is handled through SmtpClient class. The class encapsulates some pretty powerful functions, including adding attachments and sending HTML emails. HTML emails are emails that are written with HTML code and are displayed while web pages. Although it depends on the email client, most clients can read HTML emails without a problem, allowing your C# application to send emails with images and formatted text. The SmtpClient class also allows developers to add headers, which can fine-tune the behavior of emails. However be aware that some SMTP servers, like Google’s, will ignore certain headers and just use information from your account. For example, setting the From field to something else will be ignored by GMail, which will automatically set the From field to your email address.

Lastly make sure SSL is enabled on the C# application. SSL is an encryption protocol and it is absolutely required or Gmail’s server will not accept your connection.