CSharp Email Tutorial
SMTP Mailserver Testing and Usage in CSharp with .NET Core and SDK Clients: Learn to Send and Receive Emails Easily Using System.Net.Mail
CSharp is a powerful language with many features. The inbuilt SMTP pacakges under System.Net.Mail
offer easy email functionality. In this post we will discuss how to send and receive email in C# and .NET core using SMTP and SDK clients.
Email sending in code
To send CSharp emails use the System.Net.Mail
package that is included with the .NET runtime. Here is an example using XUnit to send en email from a MailSlurp SMTP server using PLAIN authentication.
using System;
using System.Net;
using System.Net.Mail;
using mailslurp.Api;
using mailslurp.Client;
using mailslurp.Model;
using Xunit;
namespace SmtpService.Tests
{
public class UnitTest0
{
[Fact]
public void CanSendWithSMTP()
{
var smtpClient = new SmtpClient("your.smtp.host")
{
Port = 2525,
};
// send email to mailbox
smtpClient.Send(from: "test@external.com", recipients: "receiver@gmail.com", subject: "This inbound", body: "Hello");
}
}
}
Configure SMTP authentication
For some SMTP Mailservers such as those provided by MailSlurp you will need to use an authentication method.
using System;
using System.Net;
using System.Net.Mail;
using mailslurp.Api;
using mailslurp.Client;
using mailslurp.Model;
using Xunit;
namespace SmtpService.Tests
{
public class UnitTest1
{
[Fact]
public void CanSendEmailWithMailSlurpSmtp()
{
var apiKey = Environment.GetEnvironmentVariable("API_KEY")
?? throw new ArgumentNullException("Missing API_KEY environment variable containing MailSlurp key");
// configure client
var config = new Configuration();
config.ApiKey.Add("x-api-key", apiKey);
var inboxController = new InboxControllerApi(config);
// create an smtp inbox
var inbox = inboxController.CreateInboxWithOptions(new CreateInboxDto(
inboxType: CreateInboxDto.InboxTypeEnum.SMTPINBOX
));
Assert.Contains("@mailslurp.mx", inbox.EmailAddress);
// get smtp host, port, password, username etc
var imapSmtpAccessDetails = inboxController.GetImapSmtpAccess();
var smtpClient = new SmtpClient(imapSmtpAccessDetails.SmtpServerHost)
{
Port = imapSmtpAccessDetails.SmtpServerPort,
Credentials = new NetworkCredential(userName: imapSmtpAccessDetails.SmtpUsername, password: imapSmtpAccessDetails.SmtpPassword),
// disable ssl recommended
EnableSsl = false
};
// send email to inbox
smtpClient.Send(from: "test@external.com", recipients: inbox.EmailAddress, subject: "This inbound", body: "Hello");
// wait for email to arrive
var waitController = new WaitForControllerApi(config);
waitController.WaitForLatestEmail(inboxId: inbox.Id, timeout: 30_000);
}
}
}
Read email in CSharp
SMTP protocols are typically used for delivery of email messages. If you wish to read emails in CSharp applications you have a few options:
- Run an SMTP server for inbound emails and take custom actions in response
- Use an IMAP package to fetch messages
- Use an email SDK like MailSlurp to send and receive
Install MailSlurp Csharp email SDK
MailSlurp is a Csharp email API service that provides free disposable email accounts (or permanent custom domains) for sending and receiving emails in CSharp applications. Create a free account to obtain an API KEY and then install the open source NuGetPackage:
Configure email client
You can configure MailSlurp to receive emails in code as follows:
using mailslurp.Api;
using mailslurp.Client;
using mailslurp.Model;
var config = new Configuration();
config.ApiKey.Add("x-api-key", "your_api_key_here");
// create an inbox controller to control inboxes
var apiInstance = new InboxControllerApi(config);
// fetch emails
var Timeout = 30000L; // max milliseconds to wait
var UnreadOnly = true; // only count unread emails
var waitForInstance = new WaitForControllerApi(config);
var email = waitForInstance.WaitForLatestEmail(inbox.Id, Timeout, UnreadOnly);
Assert.NotNull(email);
Assert.Equal("Hello", email.Subject);
Assert.Contains("Your code is: ", email.Body);